繁体   English   中英

Java Jackson:JSON值未知

[英]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,但我首先需要建模(不是)...

我的问题很简单:如何使我的代码足够灵活以适应类型...

如果可以是IntegerListString则可以将其声明为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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM