How to convert List to a JSON Object using GSON?

前端 未结 4 434
你的背包
你的背包 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 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);
    

提交回复
热议问题