MrPencil
MrPencil

Reputation: 964

The constructor JsonPrimitive(Object) is not visible

I am trying to wrapp an arrayList as Json string to send it to the Server with the Gson library but I am getting this error The constructor JsonPrimitive(Object) is not visible.

How can I fix that?

I appreciate any help.

SelectedRoute 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;
        }


    }

Upvotes: 0

Views: 1065

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279920

A JSON primitive is any of

string
number
object
array
true
false
null

and these are represented with Gson's JsonPrimitve with four constructors: one for Boolean, one for String, one for Number, and one for Character (a one character String). JsonPrimitive has a package private constructor which could accept your ArrayList value but, being package private, it is not accessible to your code.

A Java ArrayList cannot be represented as a JSON primitive. It should be a JSON array.


You've now edited your question, but here's a sample for building up a JsonObject directly

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

Upvotes: 1

Related Questions