AI智能
改变未来

fastjson入门学习(3)


FastJson入门学习

初学者入门学习,多多指正

json方法 描述
JSON.parseObject(String str, Class<?>) 将json字符串转换为java对象
JSON.toJSONString(Object object) 将java对象转换为json字符串
JSON.parseArray(String str, Class<?>) 将json字符串转换为指定类型的数组形式
构建People实体类
public class People {private String name;private int age;public People() {}public People(String name, int age) {this.name = name;this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}@Overridepublic String toString() {return \"User{\" +\"name=\'\" + name + \'\\\'\' +\", age=\" + age +\'}\';}}
构建GroupPeople实体类
public class PeopleGroup {private String name;private List<People> users = new ArrayList<>();public PeopleGroup() {}public PeopleGroup(String name, List<People> users) {this.name = name;this.users = users;}public String getName() {return name;}public void setName(String name) {this.name = name;}public List<People> getUsers() {return users;}public void setUsers(List<People> users) {this.users = users;}@Overridepublic String toString() {return \"UserGroup{\" +\"name=\'\" + name + \'\\\'\' +\", users=\" + users +\'}\';}}
测试
public class FastJsonTest {public static void main(String[] args) {//构建用户user1People peo1 = new People();peo1.setName(\"zhangsan\");peo1.setAge(12);//构建用户user2People peo2 = new People();peo2.setName(\"root\");peo2.setAge(13);//构建用户组对象PeopleGroup group = new PeopleGroup();group.setName(\"userGroup\");group.getUsers().add(peo1);group.getUsers().add(peo2);//用户组对象转json串String s = JSON.toJSONString(group);System.out.println(\"jsonString:\"+s);//json串转用户组对象PeopleGroup group1 = JSON.parseObject(s, PeopleGroup.class);System.out.println(\"gourpJavaBean:\"+group1);//构建用户对象数组People[] people = new People[2];people[0] = peo1;people[1] = peo2;//用户对象数组转jsonString s1 = JSON.toJSONString(people);System.out.println(\"objcArray-jsonString:\"+s1);//JSON串转用户对象列表List<People> users1 = JSON.parseArray(s1, People.class);System.out.println(\"jsonStr-UserObject:\"+users1);}}
结果展示
D:\\JDK_IDEA\\jdk\\bin\\java.exe ...jsonString:{\"name\":\"userGroup\",\"users\":[{\"age\":12,\"name\":\"zhangsan\"},{\"age\":13,\"name\":\"root\"}]}gourpJavaBean:UserGroup{name=\'userGroup\', users=[User{name=\'zhangsan\', age=12}, User{name=\'root\', age=13}]}objcArray-jsonString:[{\"age\":12,\"name\":\"zhangsan\"},{\"age\":13,\"name\":\"root\"}]jsonStr-UserObject:[User{name=\'zhangsan\', age=12}, User{name=\'root\', age=13}]
赞(0) 打赏
未经允许不得转载:爱站程序员基地 » fastjson入门学习(3)