Gson的fromJson()方法把json字符创转为实体
直接上代码:
1.先看Person实体类
1 import lombok.Data; 2 3 @Data 4 public class Person { 5 6 private String name; 7 8 private int age; 9 }
2.User类
1 import lombok.Data; 2 3 import java.util.List; 4 5 @Data 6 public class User { 7 8 private List<Person> personList; 9 }
3.运行例子
1 public static void main(String[] args) { 2 3 5 String json = "{'name':'wyz','age':25}"; 6 7 Person person = new Gson().fromJson(json, Person.class); 8 9 System.out.println(person); 10 11 String json1 = "{'personList':[{'name':'wyz','age':25},{'name':'wyz1','age':26}]}"; 12 13 User user = new Gson().fromJson(json1, User.class); 14 15 System.out.println(user); 16 17 String json2 = "[{'name':'wyz','age':25},{'name':'wyz1','age':26}]"; 18 19 List<Person> personList = new Gson().fromJson(json2, new TypeToken<List<Person>>() { 20 }.getType()); 21 22 System.out.println(personList); 23 }
4.演示结果
hello world!!!