首先檢查是否是 objectMapper.enableDefaultTyping(); 的受害者。優先考慮刪除該配置。
使用Jackson把數組的json字符串反序列化為List時候報了個JsonMappingException。
java.lang.UnsupportedOperationException: com.fasterxml.jackson.databind.JsonMappingException: Unexpected token (START_OBJECT), expected VALUE_STRING: need JSON String that contains type id (for subtype of java.util.List)
at [Source: [ ......
找到問題代碼,粗看似乎沒什么問題?
List<MyObject> objectList = objectMapper.readValue(jsonString, new TypeReference<List<MyObject>>() {}); //jsonString是個json對象的數組
注意到異常信息“need JSON String that contains type id (for subtype of java.util.List)”。想了一會兒,好吧,有答案了。
List<MyObject> objectList = objectMapper.readValue(jsonString, new TypeReference<ArrayList<MyObject>>() {}); //jsonString是個json對象的數組
其實,有一種比較老派的反序列化為List的方式...
List<MyObject> objectList = Arrays.asList(objectMapper.readValue(jsonString, MyObject[].class)); //jsonString是個json對象的數組
當對一些較復雜的對象進行反序列化時,例如擁有接口類型成員變量的類。舉個栗子:
@Data public class TypeValue { private Integer type; private List<Integer> value; }
有上面這個類,需要把json字符串反序列化成 Map<String, TypeValue> 這樣的對象,怎么做?
可以在TypeValue這個類中使用 @JsonCreator 注解解決。
@Data public class TypeValue { private Integer type; private List<Integer> value; @JsonCreator //為Jackson提供構造函數 public TypeValue(@JsonProperty("type") final Integer type, @JsonProperty("value") final int[] value) { this.type= type; this.value = Ints.asList(value); } }
Jackson能夠把[]數組轉換為List。因此可以用以上方法繞過Jackson的限制。
以上使用了guava和lombok