Как разобрать список пользовательских классов с помощью Jackson API? - PullRequest
0 голосов
/ 27 июня 2019

Я пытаюсь проанализировать JSON, как показано ниже, с помощью API Джексона.

{
    "name": "John", 
    "id": 1, 
    "details": [
        {
            "item": 2, 
            "count": 10
        },
        {
            "item": 3, 
            "count": 5
        },
    ]
}

Целевые классы определены как:

public class Proposal {

    private String name;

    private Integer id;

    private List<Detail> details = new ArrayList<>();

    // Setters and getters
}

public class Detail {

    private Integer item;

    private Integer count;

    // Setters and Getters
}

Я пытался использовать собственные массивы, но безуспешно. Какие аннотации и классы я должен использовать или создать, чтобы преобразование работало?

Ответы [ 2 ]

0 голосов
/ 27 июня 2019

используйте этот код

package com;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itextpdf.io.IOException;

import java.util.ArrayList;
import java.util.List;

public class Demo {
    public static void main(String[] args) {
        String jsonStr = "{\n" +
                "    \"name\": \"John\", \n" +
                "    \"id\": 1, \n" +
                "    \"details\": [\n" +
                "        {\n" +
                "            \"item\": 2, \n" +
                "            \"count\": 10\n" +
                "        },\n" +
                "        {\n" +
                "            \"item\": 3, \n" +
                "            \"count\": 5\n" +
                "        }\n" +
                "    ]\n" +
                "}";

        ObjectMapper mapper = new ObjectMapper();
        try{
            Proposal proposal =  mapper.readValue(jsonStr,Proposal.class);
            System.out.println(proposal);
        }catch(Exception ioe){
            ioe.printStackTrace();
        }

    }
}


class Proposal {

    private String name;

    private Integer id;

    private List<Detail> details;

    public String getName() {
        return name;
    }

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

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public List<Detail> getDetails() {
        return details;
    }

    public void setDetails(List<Detail> details) {
        this.details = details;
    }

    // Setters and getters
}

class Detail {

    private Integer item;

    private Integer count;

    public Integer getItem() {
        return item;
    }

    public void setItem(Integer item) {
        this.item = item;
    }

    public Integer getCount() {
        return count;
    }

    public void setCount(Integer count) {
        this.count = count;
    }
}

У вас в строке json одна запятая

0 голосов
/ 27 июня 2019

Существует очень полезный сайт jsonschema2pojo , позволяющий генерировать код Java на основе примера JSON.Учитывая ваш пример, он сгенерировал:

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({
"name",
"id",
"details"
})
public class Proposal {

@JsonProperty("name")
private String name;
@JsonProperty("id")
private Integer id;
@JsonProperty("details")
private List<Detail> details = null;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();

@JsonProperty("name")
public String getName() {
return name;
}

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

@JsonProperty("id")
public Integer getId() {
return id;
}

@JsonProperty("id")
public void setId(Integer id) {
this.id = id;
}

@JsonProperty("details")
public List<Detail> getDetails() {
return details;
}

@JsonProperty("details")
public void setDetails(List<Detail> details) {
this.details = details;
}

@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}

@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...