Given below the Json file
[
"a",
"b",
"c"
]
I need to create POJO class for above Json. I tried below code
public class Elements{
public String element;
public Elements(String element){
this.element = element;
}
}
.........
public class OuterElement{
Elements[] elements;
//Getter and Setter
}
But I get below exception
com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of [...] out of START_ARRAY token
How should be the POJO class in this case?
You need to create constructor which takes List<String> parameter and annotate it with @JsonCreator. Simple example below:
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
}
Above code prints:
OuterElement{elements=[Element{value='a'}, Element{value='b'}, Element{value='c'}]}
You can use array or list:
["a","b","c"] -> String[] elements;
["a","b","c"] -> List elements;
{"elements":["a","b","c"]} -> class YourPOJO {String[] elements;}
And remember that you need getters, setters and a default constructor
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With