json格式数据与复杂java对象的互转,

andyqian 发布于 2015/04/18 16:28
阅读 3K+
收藏 0

在使用fastjson转换复杂java对象时有如下疑问: 

@Test
public void testJavaTojson(){
School school = new School();
school.setOld(12);
school.setSchoolName("schoolName");
List<User> list = new ArrayList<User>();
User user1 = new User();
user1.setAge(20);
user1.setName("userName");
user1.setPosition("POSTION");
user1.setSchool("school");
user1.setSex("sex");
list.add(user1);
school.setUserList(list);
String json = JSONObject.toJSONString(school);
//json格式的数据是: {"old":12,"schoolName":"schoolName","userList":[{"age":20,"name":"userName","position":"POSTION","school":"school","sex":"sex"}]}
School result = ConvertJavaObject(json);
}
/**
*  将json格式的数据转换为 Sehool对象()
* @param jsonData json格式的数据
* @return
*/
private School ConvertJavaObject(String jsonData){
JSONObject object = JSONObject.parseObject(jsonData);
School sechool = object.parseObject(jsonData,School.class);
List<User> list = JSONObject.parseArray(object.getString("userList"),User.class);
sechool.setUserList(list);
return sechool;
}
上述将json格式的数据转换为sechool对象时,比较笨挫,请问大家如何能优化上述方法,

加载中
0
linxp
linxp
gson不错。去试试
andyqian
andyqian
嗯嗯,
0
asdf10
asdf10

直接School result = JSON.parseObject(json, School.class); 就可以了

andyqian
andyqian
回复 @asdf10 : 今天又重新测试了下,是有值的,应该是太粗心了,
asdf10
asdf10
回复 @划不出的界限 : 我这试过了,可以正常解析的
andyqian
andyqian
但是其中的user集合会是空的
返回顶部
顶部