R.G.
R.G.

Reputation: 11

How to convert json string in Java POJO

I tried to convert a json string from a WS to my own Java POJO, but I couldn't find the way.

Here is the response that I got from WS:

{
    "result": ["", {
        "dataset": [{
            "PLCode": "027",
            "PLType": "P",
            "PList": "BOSCH",
            "PartNumber": "0986452041",
            "Description": "FILTRO OLIO",
            "F": "",
            "DC": "F46",
            "Price": "12,2",
            "Picture": "",
            "N": "",
            "O": "027"
        }, {
            "PLCode": "484",
            "PLType": "P",
            "PList": "BRC",
            "PartNumber": "BRF1101",
            "Description": "FILTRO OLIO AVVITABILE",
            "F": "",
            "DC": " ",
            "Price": "9,11",
            "Picture": "",
            "N": "",
            "O": "484"
        }]
    }]
}

I tried differents ways, for example:

public class Test {

    private Result result;

    public Result getResult() {
        return result;
    }

    public void setResult(Result result) {
        this.result = result;
    }
}

public class Result {

    private String errorDescription;

    private List<Dataset> dataset;

    public String getErrorDescription() {
        return errorDescription;
    }

    public void setErrorDescription(String errorDescription) {
        this.errorDescription = errorDescription;
    }

    public List<Dataset> getDataset() {
        return dataset;
    }

    public void setDataset(List<Dataset> dataset) {
        this.dataset = dataset;
    }
}

And when I try to parse doing: Test test = new Test(); test = objectMapper.readValue(message, Test.class);

I got the next error:

ERROR - RequestKromedaService.getKromedaAMReferences(142) : com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of com.beans.Result out of START_ARRAY token

Could you please help me?

Thanks in advance

Upvotes: 1

Views: 354

Answers (2)

M Sach
M Sach

Reputation: 34424

In json

below represent object

{
    color: "red",
    value: "#f00"
}

below represent array

[
    {
        color: "red",
        value: "#f00"
    },
    {
        color: "green",
        value: "#0f0"
    }
]

Going by this notation

result should be an array/list in test class

Upvotes: 0

Michael Lloyd Lee mlk
Michael Lloyd Lee mlk

Reputation: 14661

Your Test object holds a single Result object, however the JSON has the result field holding an array of objects. The item in the array is a string, followed by what looks like a Result object.

Upvotes: 4

Related Questions