0

In one of my libraries say libA, I am reading a JsonArray (with string values in it) from JsonObject and converting it to String[] before adding it to an intent as extra and then I pass down that intent to another activity say activityA. I am reading from intent in activityA and creating a JsonObject out of it for use later, but am not able to add an array directly to a JsonObject.

Code in libA:

JsonObject metadata; // This has the JsonArray in it.
final String[] bookIdsArray = new Gson().fromJson(metadata.get("bookIds") , String[].class);
testIntent.putExtra("bookIds", bookIdsArray);

Code in activityA:

final JsonObject activityMetadata = new JsonObject();
activityMetadata.addProperty("bookIds", String.valueOf(intent.getStringArrayExtra("bookIds")));

addProperty method of JsonObject only accepts String, Number, Boolean or Character and another method called 'add' only accepts JsonElement. How can I directly add array to it?

tech_human
  • 6,592
  • 16
  • 65
  • 107
  • Possible duplicate of [java primitive array to JSONArray](https://stackoverflow.com/questions/25258529/java-primitive-array-to-jsonarray) – urgentx Nov 29 '18 at 00:20
  • I want to add an array in JsonObject. The link is for converting array in JsonArray. – tech_human Nov 29 '18 at 01:17

1 Answers1

0

Use the JsonObject method add(String property, JsonElement value) as JsonArray extends JsonElement.

String[] idsFromIntent = intent.getStringArrayExtra("bookIds");
JsonArray bookIds = new JsonArray();
    for (String id : idsFromIntent) {
        bookIds.add(id);
    }
activityMetadata.add("bookIds", bookIds);
urgentx
  • 3,832
  • 2
  • 19
  • 30