构造函数 JsonPrimitive(Object) 不可见

The constructor JsonPrimitive(Object) is not visible

我正在尝试将 arrayList 包装为 Json 字符串以使用 Gson 库将其发送到服务器,但我收到此错误 The constructor JsonPrimitive(Object) is not visible.

我该如何解决?

感谢任何帮助。

选择的路线class:

public class SelectedRoute {

    ArrayList<Integer> selected;

    public SelectedRoute(ArrayList<Integer> selected) {
        this.selected = selected;
    }

    public ArrayList<Integer> getSelected() {
        return selected;
    }

    public void setSelected(ArrayList<Integer> selected) {
        this.selected = selected;
    }


}

SelectedRouteSerializer class:

   public class SelectedRouteSerializer implements JsonSerializer<SelectedRoute>{

        @Override
        public JsonElement serialize(SelectedRoute select, Type arg1,
                JsonSerializationContext arg2) {
            JsonObject result = new JsonObject();
              //The error is here.
            result.add("selected", new JsonPrimitive(select.getSelected()));


            return result;
        }


    }

A JSON primitive

中的任何一个
string
number
object
array
true
false
null

这些用 Gson 的 JsonPrimitve 表示,有四个构造函数:一个用于 Boolean,一个用于 String,一个用于 Number,一个用于 [=16] =](一个字符 String)。 JsonPrimitive 有一个包私有构造函数,它可以接受您的 ArrayList 值,但是由于包私有,您的代码无法访问它。

A Java ArrayList 不能表示为 JSON 原语。它应该是一个 JSON 数组。


您现在已经编辑了您的问题,但这里有一个直接构建 JsonObject

的示例
ArrayList<Integer> arrayList = new ArrayList<>(Arrays.asList(1,2,3));
JsonObject jsonObject = new JsonObject();
JsonArray jsonArray = new JsonArray();
for (Integer value : arrayList) {
    jsonArray.add(new JsonPrimitive(value));
}
jsonObject.add("selected", jsonArray);