(1)将 java 实体对象与json字符串互转
public class Helloworld {
private void jsonParseObject() throws Exception {
String student json s = "{\"name\":\"Lily\", \"age\":\"9\"}";
StudentPo studentPo = JSON.parseObject(studentJsons, StudentPo.class);
System.out.println("解析json字符串成java实体对象其属性age值:" + studentPo.getAge());
String studentConvertJs = JSON.toJSONString(studentPo);
System.out.println("把java实体对象转换成json字符串:" + studentConvertJs);
}
public static void main(String[] args) throws Exception {
// 测试代码
new Helloworld().jsonParseObject();
}
}
(2)java集合List转成json字符串 或 把json字符串集合转化成java集合对象
public class Helloworld {
private void jsonParseObject() throws Exception {
StudentPo studentPoV1 = new StudentPo();
StudentPo studentPoV2 = new StudentPo();
studentPoV1.setAge("1");
studentPoV1.setName("n1");
studentPoV2.setName("n2");
studentPoV2.setAge("2");
List<StudentPo> spoList = new ArrayList<StudentPo>();
spoList.add(studentPoV1);
spoList.add(studentPoV2);
String listJson = JSONArray.toJSONString(spoList);
System.out.println("java集合List转成json字符串:"+ listJson);
List<StudentPo> jsonConvertList = JSONArray.parseArray(listJson, StudentPo.class);
System.out.println("把json字符串集合转化成java集合对象:" + jsonConvertList.get(0).getName());
}
public static void main(String[] args) throws Exception {
// 测试代码
new Helloworld().jsonParseObject();
}
}