【发布时间】:2016-07-31 12:56:39
【问题描述】:
我有一个 json 格式,我正在使用 Jackson API 将其转换为 Java 对象模型。我正在使用Jaxsonxml 2.1.5 解析器。 json响应如下图。
{
"response": {
"name": "states",
"total-records": "1",
"content": {
"data": {
"name": "OK",
"details": {
"id": "1234",
"name": "Oklahoma"
}
}
}
}
}
现在 json 响应格式已更改。如果total-records 是1,则details 将是一个具有id 和name 属性的对象。但如果total-records 大于1,则details 将是一个对象数组,如下所示:
{
"response": {
"name": "states",
"total-records": "4",
"content": {
"data": {
"name": "OK",
"details": [
{
"id": "1234",
"name": "Oklahoma"
},
{
"id": "1235",
"name": "Utah"
},
{
"id": "1236",
"name": "Texas"
},
{
"id": "1237",
"name": "Arizona"
}
]
}
}
}
}
我的 Java Mapper 类与之前的 json 响应如下所示。
@JsonIgnoreProperties(ignoreUnknown = true)
public class MapModelResponseList {
@JsonProperty("name")
private String name;
@JsonProperty("total-records")
private String records;
@JsonProperty(content")
private Model model;
public Model getModelResponse() {
return model;
}
public void setModel(Model model) {
this.model = model;
}
}
客户代码
package com.test.deserializer;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com..schema.model.Person;
public class TestClient {
public static void main(String[] args) {
String response1="{\"id\":1234,\"name\":\"Pradeep\"}";
TestClient client = new TestClient();
try {
Person response = client.readJSONResponse(response1, Person.class);
} catch (Exception e) {
e.printStackTrace();
}
}
public <T extends Object> T readJSONResponse(String response, Class<T> type) {
ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
T result = null;
try {
result = mapper.readValue(response, type);
} catch (Exception e) {
e.printStackTrace();
}
return (T) result;
}
}
现在基于total-records 如何处理映射到Model 或Model 对象列表。请告诉我。
【问题讨论】: