48

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 -

{  
   "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?

2
  • 1
    The JSON you have shown is not a JSON array it is a JSON object. Commented Jan 11, 2015 at 23:31
  • 1
    oops sorry, yes it is JSON Object. Let me rephrase the question. Commented Jan 11, 2015 at 23:32

5 Answers 5

92

There is a sample from google gson documentation on how to actually convert the list to 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 type of list in toJson method and pass the list object to convert it to json string or vice versa.

Sign up to request clarification or add additional context in comments.

2 Comments

This is unnecessary and won't produce the JSON they asked for.
This won't create any key name for json. How to create a key name as OP expected?
47

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

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

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

Comments

15

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 of

{"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 pretty printing. To do so use

Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(dataResponse);

Comments

0

Make sure to convert your collection to an Array first:

Gson().toJson(objectsList.toTypedArray(), Array<CustomObject>::class.java)

Comments

-4

We can also use another workaround by first creating an array of myObject then convert them into list.

final Optional<List<MyObject>> sortInput = Optional.ofNullable(jsonArgument)
                .map(jsonArgument -> GSON.toJson(jsonArgument, ArrayList.class))
                .map(gson -> GSON.fromJson(gson, MyObject[].class))
                .map(myObjectArray -> Arrays.asList(myObjectArray));

Benifits:

  • we are not using reflection here. :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.