我還在學習如何使用傑克遜...的Java傑克遜:JSON值未知
所以我有了一個值,有時是一個整數,一個長字符串或列表
一個JSON對象值:整數
{
"id":1,
"active":1,
"name":"name1",
"value":155,
...
值:字符串
{
"id":2,
"active":1,
"name":"name2",
"value":"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book...",
...
值:列表
{
"id":3,
"active":1,
"name":"name3",
"value":[
"One",
"Two",
"Three",
"Four"],
...
所以大家聚在一起的樣子......
{
{
"id":1,
"active":1,
"name":"name1",
"value":155,
...
},
{
"id":2,
"active":1,
"name":"name2",
"value":"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book...",
...
},
{
"id":3,
"active":1,
"name":"name3",
"value":[
"One",
"Two",
"Three",
"Four"],
...
}
}
這裏我POJO型號
@JsonIgnoreProperties(ignoreUnknown=true)
@JsonAutoDetect(fieldVisibility= JsonAutoDetect.Visibility.ANY)
public class OQScoresRows {
private int id;
private int active;
private String name;
private List<String> value;
... ...
這裏是我的映射器代碼
ObjectMapper mapper = new ObjectMapper();
try{
POJO obj = mapper.readValue(<JSONOBJECT>, POJO.class);
}catch(JsonParseException e){
return mapper.writeValueAsString(e);
}
問題是,當我執行我的代碼,我收到以下錯誤:
com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of VALUE_NUMBER_INT token
很明顯,我認爲這正在發生,因爲「值」可以包含三種不同類型中的一種,我怎麼做我的代碼足夠的靈活性,以適應類型......我總能在其他方法檢測是否值是一個整數,列表或字符串,但我首先需要模型(不是我)...
我的問題很簡單:我如何使我的代碼足夠靈活,以適應類型...
使用列表雖然反序列化,檢查列表是否只包含1個或更多的元素。如果它只包含1個元素,請嘗試將其解析爲long或int。如果失敗,它是一個字符串。當然,這不是一個好方法,也許不是有1個值字段,而應該有4個字段,並且在反序列化時使用jsonignoreproperties –
opensam
首先,您需要將單個值視爲數組,您可以通過配置ObjectMapper來實現, - ''objectMapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);' 然後,你想把'int'當作String來處理,你可以用下面的註解來實現: '@JsonDeserialize(using = StringDeserializer.class,as = String。類)私人列表值;' –
nazlo