Search code examples
javajsonjettison

SimpleJson: String to JSONArray


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?


Solution

  • 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.