简体   繁体   English

如何使用 GSON 将列表转换为 JSON 对象?

[英]How to convert List to a JSON Object using GSON?

I have a List which I need to convert into JSON Object using GSON.我有一个列表,需要使用 GSON 将其转换为 JSON 对象。 My JSON Object has JSON Array in it.我的 JSON 对象中有 JSON 数组。

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 -下面是我的代码,我需要在其中将列表转换为 JSON 对象,其中包含 JSON 数组 -

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 -到目前为止,我在 List 中只有两个项目 - 所以我需要这样的 JSON 对象 -

{  
   "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?做这个的最好方式是什么?

There is a sample from google gson documentation on how to actually convert the list to json string: google gson 文档中有一个关于如何将列表实际转换为json字符串的示例:

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. 您需要在toJson方法中设置列表类型并传递list对象以将其转换为json字符串,反之亦然。

If response in your marshal method is a DataResponse , then that's what you should be serializing. 如果您的marshal方法中的responseDataResponse ,那么您应该序列化。

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

That will give you the JSON output you are looking for. 这将为您提供您正在寻找的JSON输出。

Assuming you also want to get json in format 假设你也希望以格式获得json

{
  "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);

确保将您的集合转换为数组:

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

We can also use another workaround by first creating an array of myObject then convert them into list. 我们还可以使用另一种解决方法,首先创建一个myObject数组,然后将它们转换为列表。

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. 我们这里没有使用反射。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM