Home > Blockchain >  How to get something iterable out of a JSON String?
How to get something iterable out of a JSON String?

Time:03-29

I am trying to parse an Object which is in JSON format like [{"id": "1", "revisionId":"2"}, {"id":"3", "revisionId":"4"}]

I want to extract the ids to be an iterable array like ["1", "3"]

I have tried using the JSONObject library but it seems when I do this:

JSONObject jsonObject = new JSONObject(obj);

it converts the object into a structure like {"empty":false} so using jsonObject.get("id") doesn't work.

CodePudding user response:

Your json string is a json array, not an object, so you can't pass that to JSONObject, but you can use a JSONArray instead. To get the list of object IDs, you can try something like:

List<String> ids = new JsonArray(obj).toList()  // turn the JSONArray into a list
        .stream()
        .map(JSONObject.class::cast)            // cast elements to JSONObjects
        .map(json -> json.getString("id"))      // extract the id from each object
        .collect(Collectors.toList());

CodePudding user response:

Hey you try to parse a json array:
'[{"id": "1", "revisionId":"2"}, {"id":"3", "revisionId":"4"}]'

into a JSONObject. Try something like that:
'{"array": [{"id": "1", "revisionId":"2"}, {"id":"3", "revisionId":"4"}]}'

Then you can access the array with new
'JSONObject(jsonString).getJSONArray("array");'

Let me know if it work for you :-)

  • Related