Search code examples
javajsonspring-bootobjectmapper

How extract the first element of a JsonArray that is an Integer and the other are JsonElements?


I'm on a Java Spring Boot project that makes API requests using RestTemplates. Trying to implement pagination, makes the new JsonArray incoming has as first element an Integer and the rest are JsonElements. Without pagination the value of the json incoming is:

[
    {
        "id":1234,
        "name": null,
        "...":...
    },...
]

And these objects with their getter and setters correctly implented. p.d I don't need all the attributes of the incoming jsonelement.

public class WorkListBean extends WorkBean{
    private List<WorkBean> lsWorkBean;
}
public class WorkBean implements Serializable {
    private static final long serialVersionUID = -...L;
    private long id;
    private String name;
}

This returns WorkListBean[] to the client and works pretty well. But with pagination implemented the incoming json is like this:

[
    1,
    {
        "id":1234,
        "name": null
    },...
]

How could I extract this first Integer of the array?

I think maybe I could use a Deserializer with a Object Mapper to make a custom object that owns a Integer and a list or array of WorkBean. But I'm a little bit lost with this terms. Can anyone confirm am pointing in a good view?

Thanks in advance,

Grettings LaGallinaturuleta


Solution

  • That's a badly designed schema. Allthough it's technically allowed, putting elements of different types in the same array will make every client suffer.

    If you can change the server side you're talking to, they should use a more user-friendly schema, like this:

    {
        "pageNumber":0,
        "size":5,
        "totalPages":4,
        "content":[
            {"studentId":"1","name":"Bryan","gender":"Male","age":20},
            {"studentId":"2","name":"Ben","gender":"Male","age":22},
            {"studentId":"3","name":"Lisa","gender":"Female","age":24},
            {"studentId":"4","name":"Sarah","gender":"Female","age":26},
            {"studentId":"5","name":"Jay","gender":"Male","age":20}
        ],
    }
    

    If not, you're going to need a custom deserializer indeed.