[英]How to deserialize JSON into java objects using Jackson
我有一个来自solr实例的JSON响应....
{"responseHeader":
{"status":0,"QTime":1,"params":{"sort":"score asc","fl":"*,score",
"q":"{! score=distance}","wt":"json","fq":"description:motor","rows":"1"}},
"response":{"numFound":9,"start":0,"maxScore":6.8823843,"docs":
[{"workspaceId":2823,"state":"MN","address1":"1313 mockingbird Lane",
"address2":"","url":"http://mydomain.com/","city":"Minneapolis",
"country":"US","id":"399068","guid":"","geo":["45.540239, -98.580473"],
"last_modified":"2012-12-12T20:40:29Z","description":"ELEC MOTOR",
"postal_code":"55555","longitude":"-98.580473","latitude":"45.540239",
"identifier":"1021","_version_":1421216710751420417,"score":0.9288697}]}}
我正在尝试将其映射到java对象:
public class Item extends BaseModel implements Serializable {
private static final long serialVersionUID = 1L;
protected Integer workspaceId;
protected String name;
protected String description;
protected String identifier;
protected String identifierSort;
protected Address address;
protected String url;
/** getters and setters eliminated for brevity **/
}
public class Address implements Serializable {
private static final long serialVersionUID = 1L;
protected String address1;
protected String address2;
protected String city;
protected String state;
protected String postalCode;
protected String country;
/** getters and setters eliminated for brevity **/
}
如何将address1,address2,city,state等映射到Item对象中的Address对象? 我一直在阅读有关Jackson注释的信息,但是从哪里开始真的没有让我惊讶。
如果使用Jackson 1.9或更高版本,则可以使用@JsonUnwrapped注解进行处理。
这是一个使用它的示例(主要从Jackson的文档中提取):
public class Name {
private String first, last;
// Constructor, setters, getters
}
public class Parent {
private int age;
@JsonUnwrapped
private Name name;
// Constructor, setters, getters
}
public static void main(String[] args) {
try {
final ObjectMapper mapper = new ObjectMapper();
final Parent parent = mapper.readValue(new File(
"/path/to/json.txt"), Parent.class);
System.out.println(parent);
} catch (final Exception e) {
e.printStackTrace();
}
}
我们最终使用了Solrj-之类的。
我们编写了自己的SolrResult对象,将其馈送到SolrJ,如下所示:
List<SolrResult> solrResults = rsp.getBeans(SolrResult.class);
然后在具有复杂或嵌套对象的SolrResult.java中,我们首先使用SolrJ批注获取字段,然后根据需要设置值。
@Field("address1")
public void setAddress1(String address1) {
this.item.getAddress().setAddress1(address1);
}
并不难,只是感到有点混乱,但它确实有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.