0

Receiving the following JSON, exactly as shown below. How would I parse this to pojo?

{"name":"test","value":"8893"},
{"name":"test2","value":"1"},
{"name":"test3","value":"68"},
{"name":"test4","value":"26824212473"}

I tried parsing the following two ways:

First method:

List<JSONPayload> payload = mapper.readValue(obj.getjSONRequest(), new TypeReference<List<JSONPayload>>() {
                });

I get; Cannot deserialize instance ofjava.util.ArrayListout of START_OBJECT token

Second method:

JSONPayload[] payload = mapper.readValue(obj.getjSONRequest(), JSONPayload[].class);

I get; Cannot deserialize instance ofcompany.JSONPayload[]out of START_OBJECT token

2
  • I guess your json was supposed to be enclosed within [...] Commented Feb 19, 2018 at 12:13
  • Even if enclosed (which I can just add when I receive it) how would you parse it? @byteHunt3r Commented Feb 19, 2018 at 12:21

1 Answer 1

3

This works. Added []. I used

payload = objectMapper.readValue(jsonFile, objectMapper.getTypeFactory().constructCollectionType(List.class, Pojo.class));

for the conversion.

App.java

public class App {

    public static void main(String[] args) {
        String jsonFile = "[{\"name\":\"test\",\"value\":\"8893\"},\n" +
                "{\"name\":\"test2\",\"value\":\"1\"},\n" +
                "{\"name\":\"test3\",\"value\":\"68\"},\n" +
                "{\"name\":\"test4\",\"value\":\"26824212473\"}]";

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.writerWithDefaultPrettyPrinter();

        List<Pojo> payload = null;

        try {
            payload = objectMapper.readValue(jsonFile, objectMapper.getTypeFactory().constructCollectionType(List.class, Pojo.class));
        } catch (IOException e) {
            e.printStackTrace();
        }

        payload.forEach(System.out::println);

    }

}

Pojo.java

class Pojo {
    private String name;
    private String value;

    public Pojo() {
        super();
    }

    public Pojo(String name, String value) {
        this.name = name;
        this.value = value;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "Pojo{" +
                "name='" + name + '\'' +
                ", value='" + value + '\'' +
                '}';
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.