I am getting below from a post request as a JSON object. (String jsonString) I am trying to extract ids into an array.
{"description":"studentIDs", "ids": ["123", "456", "789"]}
I have to extract "ids" into a java array.
I have to use com.google.gson library.
I tried below code but it gives me error.
JsonObject jsonObject = JsonParser.parseString(jsonString).getAsJsonObject();
JsonArray arrJson = jsonObject.getAsJsonArray("ids");
String[] arr = new String[arrJson.size()];
for(int i = 0; i < arrJson.size(); i++)
arr[i] = arrJson.get(i); //Type mismatch: cannot convert from JsonElement to String
Try calling
getAsString()to get the string value from theJsonElement:Note it is likely cleaner to deserialize the JSON directly into a Java object:
Output for both approaches: