2017-01-09 46 views
0

我有一個JSON響應,它看起來像下面如何解析使用Sprint的休息模板

{ 
 
    "resourceType": "Topic", 
 
    "metadata": { 
 
    "lastUpdated": "2016-12-15T14:51:33.490-06:00" 
 
    }, 
 
    "entry": [ 
 
    { 
 
     "resource": { 
 
     "resourceType": "Outcome", 
 
     "issue": [ 
 
      { 
 
      "response": "error", 
 
      "code": "exception" 
 
      }, 
 
      { 
 
      "response": "success", 
 
      "code": "informational" 
 
      }, 
 
\t \t { 
 
      "response": "success", 
 
      "code": "informational" 
 
      } 
 
     ] 
 
     } 
 
    }, 
 
    { 
 
     "resource": { 
 
     "resourceType": "Data", 
 
     "id": "80", 
 
     "subject": { 
 
      "reference": "dataFor/80" 
 
     }, 
 
     "created": "2016-06-23T04:29:00", 
 
     "status": "current" 
 
     } 
 
    }, 
 
\t { 
 
     "resource": { 
 
     "resourceType": "Data", 
 
     "id": "90", 
 
     "subject": { 
 
      "reference": "dataFor/90" 
 
     }, 
 
     "created": "2016-06-23T04:29:00", 
 
     "status": "current" 
 
     } 
 
    } 
 
    ] 
 
}

數據和結果類擴展資源混合子對象的JSON。

我正在使用Spring RestTemplate.getForObject(url,someClass)。我得到以下錯誤

has thrown exception, unwinding now 
 
org.apache.cxf.interceptor.Fault: Could not read JSON: Unrecognized field "response" (Class com.model.Resource), not marked as ignorable 
 
at [Source: [email protected]e67a;

據我瞭解,JSON是沒有得到解析到子類資源。我想要做類似RestTemplate.getForObject(url,someClass)的東西,但這不被java泛型(通配符)支持。請幫助

+0

告訴我們你的'com.model.Resource'。 – Arpit

回答

1

您需要使用jackson反序列化爲動態類型,並使用resourceType作爲字段來指示實際類型。將這些添加到您的資源類。

@JsonTypeInfo(property = "resourceType", use = Id.NAME) 
@JsonSubTypes({ @Type(Data.class), 
      @Type(Outcome.class) 
      }) 

這是一個將證明行爲的單元測試。

@Test 
public void deserializeJsonFromResourceIntoData() throws IOException { 
    Data data = (Data) new ObjectMapper().readValue("{" + 
      "  \"resourceType\": \"Data\"," + 
      "  \"id\": \"80\"," + 
      "  \"subject\": {" + 
      "   \"reference\": \"dataFor/80\"" + 
      "  }," + 
      "  \"created\": \"2016-06-23T04:29:00\"," + 
      "  \"status\": \"current\"" + 
      "  }", Resource.class); 

    assertEquals(Integer.valueOf(80), data.getId()); 
    assertEquals("dataFor/80", data.getSubject().getReference()); 
} 

至於演員,我在這裏所做的只是爲了證明它的工作原理,但是,要真正多態的,你可能希望有資源包含所有你需要的行爲,然後一切都只是資源。

+0

感謝lane.maxwell。我可以將它投射到結果中,檢查它爲什麼不投射到數據。會及時向大家發佈。 –

+0

查看我的編輯,我已經包含了單元測試。你可能只想傳遞Resource對象,而不是底層的實現。 –

+0

感謝lane.maxwell。完美工作。你是救世主。 –