How to extract ids into a java array?

67 Views Asked by At

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
1

There are 1 best solutions below

0
Sash Sinha On BEST ANSWER

Try calling getAsString() to get the string value from the JsonElement:

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.util.Arrays;

class Main {
    public static void main(String[] args) {
        String jsonString = "{\"description\":\"studentIDs\", \"ids\": [\"123\", \"456\", \"789\"]}";
        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).getAsString();
        }
        System.out.println(Arrays.toString(arr));
    }
}

Note it is likely cleaner to deserialize the JSON directly into a Java object:

import com.google.gson.Gson;

import java.util.List;

class StudentIDs {
    private String description;
    private List<String> ids;

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public List<String> getIds() {
        return ids;
    }

    public void setIds(List<String> ids) {
        this.ids = ids;
    }
}


class Main {
    public static void main(String[] args) {
        String jsonString = "{\"description\":\"studentIDs\", \"ids\": [\"123\", \"456\", \"789\"]}";
        Gson gson = new Gson();
        StudentIDs studentIDs = gson.fromJson(jsonString, StudentIDs.class);
        System.out.println(studentIDs.getIds());
    }
}

Output for both approaches:

[123, 456, 789]