在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类应该如何?

最佳答案

您需要创建带有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'}]}

09-10 08:48
查看更多