简体   繁体   中英

Deserialize a JSON containing a list of objects using Gson

I'm trying to deserialize a JSON which containes a String and a list of objects in my Spring web application.

JSON

[
{
    "jsonrpc":"2.0",
    "result":[
    {
    "event":{
        "id":"27809810",
        "name":"Spezia v Trapani",
        "countryCode":"IT",
        "timezone":"Europe/London",
        "openDate":"2016-05-28T16:30:00.000Z" 
    },
    "marketCount":13
    },
    {
    "event":{
        "id":"27811083",
        "name":"Torino U19 v Atalanta U19",
        "countryCode":"IT",
        "timezone":"Europe/London",
        "openDate":"2016-05-29T16:15:00.000Z" 
    },
    "marketCount":18
    },
...
]

My classes are:

ListEventsResponse class

public class ListEventsResponse {
    private String jsonrpc;
    private List<ListEventsResult> result;

    public ListEventsResponse() { }

    public String getJsonrpc() {
        return jsonrpc;
    }

    public void setJsonrpc(String jsonrpc) {
        this.jsonrpc = jsonrpc;
    }

    public List<ListEventsResult> getResult() {
        return result;
    }

    public void setResult(List<ListEventsResult> result) {
        this.result = result;
    }
}

ListEventsResult class

public class ListEventsResult {
    private Event event;
    private int marketCount;

    public ListEventsResult() { }

    public Event getEvent() {
        return event;
    }

    public void setEvent(Event event) {
        this.event = event;
    }

    public int getMarketCount() {
        return marketCount;
    }

    public void setMarketCount(int marketCount) {
        this.marketCount = marketCount;
    }
}

I have also Event class , composed by 5 String (id, name, etc.).

Controller

[...]
ListEventsResponse listEvents = new Gson().fromJson(response.toString(), ListEventsResponse.class);         
List<ListEventsResult> eventsList = listEvents.getResult();
    return new ModelAndView("page", "eventsList", eventsList);

My .jsp page

[...]
<c:forEach items="${eventsList}" var="listEventsResult">
   Match: <c:out value="${listEventsResult.name}"/>
</c:forEach>
[...]

My code runs and doesn't give any error, but no match is shown on my page, in fact listEvents doesn't contains any object.

I can't understand how to deserialize properly the list of objects, so my question is: which logic is behind the deserialization of a json which contains a list of objects?

I post my code just to explain better my problem.

As you have a Json Array as response , you need to deserialize like below

    Gson gson = new Gson();
    Type type = new TypeToken<List<ListEventsResponse>>(){}.getType();
    List<ListEventsResponse> events = (List<ListEventsResponse>) gson.fromJson(response.toString(), type);

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