Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
217 views
in Technique[技术] by (71.8m points)

java - How to convert 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 -

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...