How to convert List to a JSON Object using GSON?

前端 未结 4 422
你的背包
你的背包 2020-12-05 17:08

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

        
相关标签:
4条回答
  • 2020-12-05 17:55

    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. :)
    0 讨论(0)
  • 2020-12-05 18:05

    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.

    0 讨论(0)
  • 2020-12-05 18:08

    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);
    
    0 讨论(0)
  • 2020-12-05 18:09

    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.

    0 讨论(0)
提交回复
热议问题