复杂的JSON怎么转换为JavaBean
{"data":{"Student":[{"studentName":"lily","studentAge":12}]}}我想从中获取studentName我用newTy...
{"data": {"Student": [{"studentName": "lily","studentAge": 12}]}} 我想从中获取studentName 我用new TypeReference<T>()形式还是获取不到
展开
2个回答
展开全部
必先创建一个java bean
public class Student {
private String studentName;
private int studentAge;
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public int getStudentAge() {
return studentAge;
}
public void setStudentAge(int studentAge) {
this.studentAge = studentAge;
}
@Override
public String toString() {
return "Student [studentName=" + studentName + ", studentAge=" + studentAge + "]";
}
}
添加fastjson 相关依赖,如果是maven 工程pom 添加
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.56</version>
</dependency>
转换过程如下:
String jsonStr = "{\"data\":{\"Student\":[{\"studentName\":\"lily\",\"studentAge\":12}]}}";
// 先转换为map
Map map = (Map)JSONObject.parse(jsonStr);
Map studentMap = (Map)map.get("data");
// Student 后面对应一个对象数组。转换方式如下。
ArrayList<Student> parseObject = JSON.parseObject(studentMap.get("Student").toString(),new TypeReference<ArrayList<Student>>(){});
System.out.println(parseObject);
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询