How to set array value in the jsonobject

I am getting the array values as

I need to construct the object as jsonObject.

So I have added like below but the returning object as an error.

How can I add the array as expected in the users.

Note: Here I am sending the users in array from a fragment to set the values in my payload

private String mUserArray; //value =["user1", "user2"]

mUserArray is added in the constructor.

final JsonArray array = new JsonArray();
array.add(mUserArray1);
final JsonObject jo = new JsonObject();
jo.addProperty("type", "value")
jo.add("usernames" , array); // If i set the userarray it failed to convert Added like this as well//new JsonPrimitive(mUserArray1)

return jo;

Expected Result: {"type": "value", "usernames":["user1", "user2"]}

Actual Result: {"type":"value","usernames":"["user1", "user2"]"}

Answer

It seems like that you added the usernames property as a string literal rather than as a JSON array. You can construct a JsonArray of strings from a Java array the following way.

    String[] userArray = {"user1", "user2"};

    JsonArray userJsonArray = new JsonArray();

    for(String user: userArray){
        userJsonArray.add(new JsonPrimitive(user));
    }

    JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("type", "value");
    jsonObject.add("usernames", userJsonArray);

Note that JsonObject::addProperty only adds primitives to the JSON object rather than arrays or objects.

Leave a Reply

Your email address will not be published. Required fields are marked *