How to convert a list to a JSON object using GSON?


I have a List which I need to convert into JSON Object using GSON. My JSON Object has JSON Array in it.

public class DataResponse {

    private List<ClientResponse> apps;

    // getters and setters

    public static class ClientResponse {
        private double mean;
        private double deviation;
        private int code;
        private String pack;
        private int version;

        // getters and setters

Below is my code in which I need to convert my List to JSON Object which has JSON Array in it -

public void marshal(Object response) {

    List<DataResponse.ClientResponse> clientResponse = ((DataResponse) response).getClientResponse();

    // now how do I convert clientResponse list to JSON Object which has JSON Array in it using GSON?

    // String jsonObject = ??

As of now, I only have two items in List - So I need my JSON Object like this -


What is the best way to do this?

If response in your marshal method is a DataResponse, then that's what you should be serializing.

Gson gson = new Gson();

That will give you the JSON output you are looking for.