如何使用Jackson将JSON反序列化为java对象

时间:2012-12-13 20:14:38

标签: java solr 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 annotations的内容,但没有任何关于我从何处开始的事情。

2 个答案:

答案 0 :(得分:2)

如果使用Jackson 1.9或更高版本,您可以使用@JsonUnwrapped注释来处理此问题。

以下是使用它的一个例子(很大程度上取决于杰克逊的文档):

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();
   }
}

答案 1 :(得分:2)

我们最终使用了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);
}

感觉有点麻烦并不难,但确实有效。