SimpleJson: String to JSONArray

mosquito87 picture mosquito87 · Feb 25, 2016 · Viewed 21.7k times · Source

I get the following JSON:

[
  {
    "user_id": "someValue"
  }
]

It's saved inside a String.

I would like to convert it to a JSONObject which fails (as the constructor assumes a JSON to start with {). As this doesn't seem to be possible I'd like to convert it to a JSONArray. How can I do that with SimpleJson?

Answer

Michael Lloyd Lee mlk picture Michael Lloyd Lee mlk · Feb 25, 2016
JSONParser parser = new JSONParser();
JSONArray array = (JSONArray)parser.parse("[{\"user_id\": 1}]");
System.out.println(((JSONObject)array.get(0)).get("user_id"));

You need to cast to a JSONArray as that is what the string contains.