【问题标题】:Creating mapping class for Json Array为 Json 数组创建映射类
【发布时间】:2019-04-02 11:50:30
【问题描述】:

在Json文件下方给出

[
  "a",
  "b",
  "c"
]

我需要为上面的 Json 创建 POJO 类。我试过下面的代码

public class Elements{
  public String element;
  public Elements(String element){
    this.element = element;
  }
}

…………

public class OuterElement{
   Elements[] elements;
   //Getter and Setter
}

但我得到以下异常

com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of [...] out of START_ARRAY token

这种情况下的POJO类应该怎么做?

【问题讨论】:

    标签: java arrays json jackson


    【解决方案1】:

    您需要创建带有List<String> 参数的构造函数并使用@JsonCreator 对其进行注释。下面的简单例子:

    import com.fasterxml.jackson.annotation.JsonCreator;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import java.util.Arrays;
    import java.util.List;
    
    public class Test {
    
        public static void main(String[] args) throws Exception {
            String json = "[\"a\",\"b\",\"c\"]";
    
            ObjectMapper mapper = new ObjectMapper();
            OuterElement outerElement = mapper.readValue(json, OuterElement.class);
    
            System.out.println(outerElement);
        }
    }
    
    class Element {
    
        private String value;
    
        public Element(String value) {
            this.value = value;
        }
    
        // getters, setters, toString
    }
    
    class OuterElement {
    
        private Element[] elements;
    
        @JsonCreator
        public OuterElement(List<String> elements) {
            this.elements = new Element[elements.size()];
            int index = 0;
            for (String element : elements) {
                this.elements[index++] = new Element(element);
            }
        }
    
        // getters, setters, toString
    }
    

    上面的代码打印:

    OuterElement{elements=[Element{value='a'}, Element{value='b'}, Element{value='c'}]}
    

    【讨论】:

      【解决方案2】:

      你可以使用数组或列表:

      ["a","b","c"] -> 字符串[] 元素;

      ["a","b","c"] -> 列出元素;

      {"elements":["a","b","c"]} -> 类 YourPOJO {String[] elements;}

      请记住,您需要 getter、setter 和默认构造函数

      【讨论】:

        【解决方案3】:

        通过您的 pojo,我们将获得如下数据,

        Java 代码

        OuterElement outerElement=new OuterElement();
                outerElement.setElements(new Elements[]{new Elements("a"),new Elements("b"),new Elements("c")});
        

        还有数据,

        {
            "elements": [
                {
                    "element": "a"
                },
                {
                    "element": "b"
                },
                {
                    "element": "c"
                }
            ]
        }
        

        这就是为什么 json 映射器无法转换的原因,数据映射器期望的是对象,但您提交的是数组,它产生了 "Can not deserialize instance of [...] out of START_ARRAY token"

        你可以像下面这样拥有pojo,

        public class Elements {
        
            @JsonProperty("0")
            public String element;
        
            public String getElement() {
                return element;
            }
        
            public void setElement(String element) {
                this.element = element;
            }
        
            public Elements(String element) {
                super();
                this.element = element;
            }
        
        
        
        }
        

        【讨论】:

          【解决方案4】:

          您可以使用http://www.jsonschema2pojo.org/ 将您的 JSON 解析为 POJO

          请注意,如果您的完整 JSON 是

          ["a","b","c"] 只能解析为列表数组。与其将其映射到对象,不如尝试以不同的方式访问 JSON。有关示例,请参阅 @jschnasse 的 answer。

          但是,如果您通常将 JSON 对象作为

          {
            "alphabet": ["a","b","c"]
          }
          

          那么http://www.jsonschema2pojo.org/会为你生成下一个POJO:

          package com.example;
          
          import java.util.HashMap;
          import java.util.List;
          import java.util.Map;
          import com.fasterxml.jackson.annotation.JsonAnyGetter;
          import com.fasterxml.jackson.annotation.JsonAnySetter;
          import com.fasterxml.jackson.annotation.JsonIgnore;
          import com.fasterxml.jackson.annotation.JsonInclude;
          import com.fasterxml.jackson.annotation.JsonProperty;
          import com.fasterxml.jackson.annotation.JsonPropertyOrder;
          
          @JsonInclude(JsonInclude.Include.NON_NULL)
          @JsonPropertyOrder({
                  "alphabet"
          })
          public class Example {
          
              @JsonProperty("alphabet")
              private List<String> alphabet = null;
              @JsonIgnore
              private Map<String, Object> additionalProperties = new HashMap<String, Object>();
          
              @JsonProperty("alphabet")
              public List<String> getAlphabet() {
                  return alphabet;
              }
          
              @JsonProperty("alphabet")
              public void setAlphabet(List<String> alphabet) {
                  this.alphabet = alphabet;
              }
          
              @JsonAnyGetter
              public Map<String, Object> getAdditionalProperties() {
                  return this.additionalProperties;
              }
          
              @JsonAnySetter
              public void setAdditionalProperty(String name, Object value) {
                  this.additionalProperties.put(name, value);
              }
          
          }
          

          【讨论】:

            猜你喜欢
            • 2012-09-28
            • 1970-01-01
            • 2016-07-05
            • 2018-05-17
            • 2017-06-01
            • 1970-01-01
            • 2019-01-09
            • 1970-01-01
            • 2023-01-31
            相关资源
            最近更新 更多