json数据转换实例

public class JsonTest {
public static void main(String[] args) {
ClassA a = new ClassA();
a.setName("className01");
List<Student> stuList = new ArrayList<>();
for(int i=0; i<3; i++){
Student stu = new Student();
stu.setName("test"+i);
stu.setAge(i);
stuList.add(stu);
}

a.setStudentList(stuList);

//bean 2 string
JSONObject jObj = JSONObject.fromObject(a);
String jsonStr = jObj.toString();
System.out.println(jsonStr);

//string 2 jsonobject
JSONObject jsonObj = JSONObject.fromObject(jsonStr);
System.out.println("class name ="+jsonObj.getString("name"));
JSONArray jsonArray = jsonObj.getJSONArray("studentList");
for(int i=0; i<jsonArray.size(); i++){
JSONObject student = (JSONObject)jsonArray.get(i);
System.out.println("name ="+student.getString("name"));
System.out.println("age ="+student.getString("age"));

}

//string 2 bean 方法1
Map<String,Class> classMap = new HashMap<>();
classMap.put("studentList", Student.class);
ClassA b = (ClassA)JSONObject.toBean(jsonObj, ClassA.class, classMap);
System.out.println("class name ="+b.getName());
List<Student> stuList02 = b.getStudentList();
for(int i=0; i<stuList02.size(); i++){
Student stu = stuList02.get(i);
System.out.println(stu.getName());
System.out.println(stu.getAge());
}

//string 2 bean 方法2
ObjectMapper objectMapper=new ObjectMapper();
ClassA c = null;
try {
c=objectMapper.readValue(jsonStr, ClassA.class);
System.out.println("class name ="+c.getName());
List<Student> stuList03 = c.getStudentList();
for(int i=0; i<stuList03.size(); i++){
Student stu = stuList03.get(i);
System.out.println(stu.getName());
System.out.println(stu.getAge());
}
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

}

package com.test.pojo;

import java.util.List;

public class ClassA {
private String name;
private List<Student> studentList;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Student> getStudentList() {
return studentList;
}
public void setStudentList(List<Student> studentList) {
this.studentList = studentList;
}
}

package com.test.pojo;

public class Student {
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}

注:1) JSONObject.fromObject(javabean)中的javabean.class必须为public,否则会报:Property '***' has no getter method

2)JSONObject.toBean可直接用于简单数据类型的Class,如果里面有复杂数据类型,需使用Map<String,Class>,

其中key为复杂数据类型的属性名,Class为复杂数据类型的类名



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值