我使用Jackson API将json格式转换为Java对象模型。我正在使用Jaxsonxml 2.1.5解析器。 json响应如下所示。使用Jackson基于条件注入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类映射看起来像下面与早期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 readJSONResponse(String response, Class 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或列表。请告诉我。
2016-07-31
zilcuanu