简体   繁体   中英

Parsing JSON list of objects

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 of java.util.ArrayList out of START_OBJECT token

Second method:

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

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

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 + '\'' +
                '}';
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM