stackoverflow
stackoverflow

Reputation: 2224

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?

Upvotes: 3

Views: 1485

Answers (4)

Scrobot
Scrobot

Reputation: 1981

You can use http://www.jsonschema2pojo.org/ to parse your JSON to POJO

Note, that if your full JSON is

["a","b","c"] It's can be parsed only as array of list. Instead of mapping it to an object try to access the JSON differently. See @jschnasse's answer for an example.

But, if you have normally JSON object as

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

then http://www.jsonschema2pojo.org/ will generate to you next 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);
    }

}

Upvotes: 0

Srinivasan Sekar
Srinivasan Sekar

Reputation: 2119

With your pojo we'll get the data as below ,

Java code

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

And data,

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

that's why json mapper to failed to convert , the data mapper was expecting is object but what you have submitted is array which produced "Can not deserialize instance of [...] out of START_ARRAY token"

you can have pojo like below,

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;
    }



}

Upvotes: 0

Michał Ziober
Michał Ziober

Reputation: 38635

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'}]}

Upvotes: 1

Vova Chornyi
Vova Chornyi

Reputation: 21

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

Upvotes: 1

Related Questions