2

我有一个从 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 对象中?我一直在阅读有关杰克逊注释的内容,但对于从哪里开始,我并没有真正跳出来。

4

2 回答 2

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();
   }
}
于 2012-12-13T20:20:03.837 回答
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);
}

这并不难,只是感觉有点乱,但它确实有效。

于 2012-12-20T07:14:52.580 回答