Gson的fromJson()方法把json字符创转为实体

时间:2024-07-10 16:35:08

直接上代码:

1.先看Person实体类

 import lombok.Data;

 @Data
public class Person { private String name; private int age;
}

2.User类

 import lombok.Data;

 import java.util.List;

 @Data
public class User { private List<Person> personList;
}

3.运行例子

 public static void main(String[] args) {

         String json = "{'name':'wyz','age':25}";

         Person person = new Gson().fromJson(json, Person.class);

         System.out.println(person);

         String json1 = "{'personList':[{'name':'wyz','age':25},{'name':'wyz1','age':26}]}";

         User user = new Gson().fromJson(json1, User.class);

         System.out.println(user);

         String json2 = "[{'name':'wyz','age':25},{'name':'wyz1','age':26}]";

         List<Person> personList = new Gson().fromJson(json2, new TypeToken<List<Person>>() {
}.getType()); System.out.println(personList);
}

4.演示结果

Gson的fromJson()方法把json字符创转为实体