Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating mapping class for Json Array

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?

like image 539
stackoverflow Avatar asked Jun 09 '26 04:06

stackoverflow


2 Answers

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'}]}
like image 138
Michał Ziober Avatar answered Jun 10 '26 19:06

Michał Ziober


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

like image 25
Vova Chornyi Avatar answered Jun 10 '26 18:06

Vova Chornyi