2012-12-13 76 views
2

我從Solr的實例回來相當JSON響應Java對象....如何反序列化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 **/ 
    } 

如何將地址1,地址2,城市,州等等映射到項目對象中的地址對象?我一直在閱讀關於Jackson annotations,但沒有真正跳到我從哪裏開始。

+0

你必須指定你所嘗試的。有不同的方法http://mattgemmell.com/2008/12/08/what-have-you-tried/ –

+0

你有沒有考慮過使用SolrJ?您可能會發現更方便,無論是解開響應還是構建查詢。 –

+0

@Eric我沒有,但完全願意看看它。你有沒有一個你認爲是開始的好地方? – kasdega

回答

2

我們結束了使用Solrj - 那種。

我們寫我們的,我們送入SolrJ像這樣自己SolrResult對象:

List<SolrResult> solrResults = rsp.getBeans(SolrResult.class); 

然後在SolrResult.java在那裏我們有我們只是第一次使用SolrJ註釋獲取字段複雜或嵌套對象,然後只需根據需要設置值...

@Field("address1") 
public void setAddress1(String address1) { 
    this.item.getAddress().setAddress1(address1); 
} 

這並不難,只是覺得有點混亂,但它確實有效。

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

我會給它一個鏡頭謝謝! – kasdega