目前面临一个问题,如何将json格式的对象列表序列化为pojo。在我的作品中使用泽西休息服务它可以消耗json。如何使用具有对象数组的json对象反序列化rest请求。
json数组
{
"subject": "hi",
"description": [
{
"subject": "hi"
},
{
"subject": "hi"
}
]
}
我的pojo课程
public class t {
private String subject;
private List<t2> description;
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public List<t2> getDescription() {
return description;
}
public void setDescription(List<t2> description) {
this.description = description;
}
}
t2.class
public class t2 {
private String subject;
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
}
答案 0 :(得分:-1)
使用TypeReference
。例如:
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonParser {
public static void main(String[] args) {
t data = null;
String json = "{\"subject\":\"hi\",\"description\":[{\"subject\":\"hi\"},{\"subject\":\"hi\"}]}";
ObjectMapper mapper = new ObjectMapper();
try {
data = mapper.readValue(json, new TypeReference<t>() { });
} catch (JsonParseException e) {
System.out.println(e.getMessage());
} catch (JsonMappingException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
}
System.out.println(data);
}
}