我使用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 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
或列表。請告訴我。
我收到一個錯誤,指出當使用上述方法時,com.fasterxml.jackson.databind.JsonMappingException:類com.test.deserializer.CustomDeserializer沒有默認(無arg)構造函數。 – zilcuanu
在發佈的代碼中添加了一個構造函數。 – AngerClown
我試着用你的方法。但仍然沒有運氣。讓我知道我的客戶代碼是否正確。我仍然得到相同的異常'com.fasterxml.jackson.databind.JsonMappingException:類com.test.deserializer.CustomDeserializer沒有默認(無arg)構造函數' – zilcuanu