[英]Java Jackson: JSON value unknown
我仍在學習如何使用Jackson。
所以我有一個JSON對象,該對象的值有時是Integer,長String或List
值:整數
{
"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
對我來說,這很明顯是因為“值”可以包含三種不同類型之一,如何使我的代碼足夠靈活以容納這些類型...我總是可以在其他方法中檢測值是否為int,List或String,但我首先需要建模(不是)...
我的問題很簡單:如何使我的代碼足夠靈活以適應類型...
如果可以是Integer
, List
和String
則可以將其聲明為Object
,並稍后使用instanceof
將其instanceof
,例如:
@JsonIgnoreProperties(ignoreUnknown=true)
@JsonAutoDetect(fieldVisibility= JsonAutoDetect.Visibility.ANY)
public class OQScoresRows {
private int id;
private int active;
private String name;
private Object value;
反序列化之后,可以編寫類似於以下內容的邏輯:
if(value instanceof Integer){
//do something after casting it to Integer
}else if(value instanceof List){
//do something after casting it to List
}else if(value instanceof String){
do something after casting it to String
}
If-else
語句適合您的問題,但是它是json對象中的所有字符串格式,因此您必須找出一種從值識別數據類型的方法。 例如,將Integer.valueOf(value)
標識為int; 以[
開頭為身份列表; 另一個是字符串類型。 您可以參考此答案 ,這是將json字符串轉換為對象或列表的一般方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.