Gson json,list,model互转
程序员文章站
2022-07-15 14:57:17
...
public class Person { private String name; private String age; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } @Override public String toString() { return name + ":" + age; } }
import java.util.ArrayList; import java.util.List; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; public class TestMain { private static String listToJson(){ Gson gson = new Gson(); List<Person> persons = new ArrayList<Person>(); for (int i = 0; i < 10; i++) { Person p = new Person(); p.setName("name" + i); p.setAge("intvalue"); persons.add(p); } String str = gson.toJson(persons); return str; } private static Person jsonToModelisDeit(){ String json = "{\"name\":\"name0\",\"age\":\"0\"}"; Gson gson = new Gson(); Person person = gson.fromJson(json, Person.class); return person; } private static List<Person> jsonToList(){ Gson gson = new Gson(); String json = "[{\"name\":\"name1\",\"age\":\"intvalue\"},{\"name\":\"name2\",\"age\":\"intvalue\"},{\"name\":\"name3\",\"age\":\"intvalue\"}]"; List<Person> ps = gson.fromJson(json, new TypeToken<List<Person>>(){}.getType()); for(int i = 0; i < ps.size() ; i++) { Person p = ps.get(i); System.out.println(p.toString()); } return ps; } public static void main(String[] args) { // String json = TestMain.listToJson(); // System.out.println(json); // // Person model = TestMain.jsonToModelisDeit(); // System.out.println(model.getName()); // System.out.println(model.getAge()); List<Person> plist = TestMain.jsonToList(); } }
<!-- google Gson --> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.6.2</version> </dependency>
下一篇: 马云谈人才培养
推荐阅读
-
Json和Map互转,三个包(org.json/net.sf.json/com.google.gson)
-
Gson json,list,model互转
-
Gson基本操作,JsonObject,JsonArray,String,JavaBean,List互转
-
简单使用Java Gson,list、map、实体类转换为json数据
-
Json和Map互转,三个包(org.json/net.sf.json/com.google.gson)
-
JSON的String字符串与Java的List列表对象的相互转换
-
JSON的String字符串与Java的List列表对象的相互转换
-
Gson json,list,model互转
-
Json转换利器Gson之实例一-简单对象转化和带泛型的List转化
-
Gson基本操作,JsonObject,JsonArray,String,JavaBean,List互转