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

I have a list that I need to convert to a JSON object using GSON. My JSON object has a JSON Array.

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 a JSON object that has a 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 = ?? } 

At the moment, I have only two items in the list. So I need my JSON object like this -

 { "apps":[ { "mean":1.2, "deviation":1.3 "code":100, "pack":"hello", "version":1 }, { "mean":1.5, "deviation":1.1 "code":200, "pack":"world", "version":2 } ] } 

What is the best way to do this?

+7
java json arrays gson
source share
3 answers

If the response in your marshal method is a DataResponse , then this is what you should serialize.

 Gson gson = new Gson(); gson.toJson(response); 

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

+20
source share

There is an example from google gson documentation on how to actually convert a list to a json string:

 Type listType = new TypeToken<List<String>>() {}.getType(); List<String> target = new LinkedList<String>(); target.add("blah"); Gson gson = new Gson(); String json = gson.toJson(target, listType); List<String> target2 = gson.fromJson(json, listType); 

You need to set the list type in the toJson method and pass the list object to convert it to json string or vice versa.

+25
source share

Assuming you also want to get json in format

 { "apps": [ { "mean": 1.2, "deviation": 1.3, "code": 100, "pack": "hello", "version": 1 }, { "mean": 1.5, "deviation": 1.1, "code": 200, "pack": "world", "version": 2 } ] } 

instead

 {"apps":[{"mean":1.2,"deviation":1.3,"code":100,"pack":"hello","version":1},{"mean":1.5,"deviation":1.1,"code":200,"pack":"world","version":2}]} 

You can use beautiful print. To do this, use

 Gson gson = new GsonBuilder().setPrettyPrinting().create(); String json = gson.toJson(dataResponse); 
+3
source share

All Articles