2017-01-09 50 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。完美工作。你是救世主。 –