2013-10-29 55 views
-1

的局部解組考慮以下JSON輸入:JAXB JSON

{ 
    "url": [ 
     { 
      "http://some_url": [ 
       { 
        "id": 1, 
        "name": "name1" 
       } 
      ] 
     } 
    ] 
} 

假設http://some_url是有效url.This可以在每個響應不同。我感興趣的是物業http://some_url的價值。但由於密鑰http://some_url可以更改,所以我無法爲此創建POJO。我只需要解開http://some_url的值。在這種情況下可能部分解組?我有一個Details類作爲我的java類。

Details類的裸機是:

@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) 
public class Details { 
    @JsonProperty("id") 
    public String id; 
    @JsonProperty("name") 
    public String name; 
} 

因爲我不知道該怎麼辦局部解組,我是這樣做的:

Map<String,String> respData = null; 
ObjectMapper mapper = new ObjectMapper(); 
respData = mapper.readValue({JSON STRING},Map.class); 

相反,我會愛以某種方式將其轉換爲我的Details類。我不太清楚如何實現這一點。

+0

要Downvoter:能否請你加你爲什麼downvoted理由嗎? –

回答

0

設法弄清楚了。感謝一些深夜編碼,stackoverflow和一些紅牛。我必須解析JSON並使用JSONObject的一部分。對此的啓發是一個類似的問題,但是那個人卻用XML解析了XML。參考:Partial Unmarshalling of an XML using JAXB to skip some xmlElement。以下是如果任何人有興趣的代碼。

POJO

@XmlRootElement(name="dummy") // Does not work if I have no @XmlRootElement. Any suggestions? 
@XmlAccessorType(XmlAccessType.FIELD) 
public class Details { 
    @XmlElement(name = "id") 
    public Double id; 
    @XmlElement(name = "name") 
    public String name; 
} 

拆封CLASS

 JSONObject obj = new JSONObject(response.getResponseBody()); // response.getResponseBody() returns a JSON string response from the API. 
     JSONArray array = obj.getJSONArray("url"); 
     for(int i=0;i < array.length() ;i++) { 
      JSONArray innerArray = array.getJSONObject(i).getJSONArray(url); // url is the http://some_url 
      JSONObject obj1 = innerArray.getJSONObject(0); 


      JSONObject obj2 = new JSONObject(); 
      // Needed to surround the JSONObject with a "dummy" property. Without this, my POJO class did not work. Is there a better way? 
      obj2.put("dummy",obj1); 


      Configuration config = new Configuration(); 
      MappedNamespaceConvention con = new MappedNamespaceConvention(config); 
      XMLStreamReader xmlStreamReader = new MappedXMLStreamReader(obj2, con); 
      JAXBContext jc = JAXBContext.newInstance(Details.class); 
      Unmarshaller unmarshaller = jc.createUnmarshaller(); 
      Details detailsPOJO = (Details) unmarshaller.unmarshal(xmlStreamReader); 
      System.out.println("USER ID:"+detailsPOJO.id); 
     }