gson 的简单使用

生成Json字符串



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(i * 5);

     persons.add(p);

}

String str = gson.toJson(persons);

json 转对象

Person person = gson.fromJson(str, Person.class);

json 转list  泛型:

List<Person> ps = gson.fromJson(str, new TypeToken<List<Person>>(){}.getType());

for(int i = 0; i < ps.size() ; i++)

{

     Person p = ps.get(i);

     System.out.println(p.toString());

}

 

你可能感兴趣的:(gson)