SimpleJson: String to JSONArray

25.2k Views Asked by At

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?

4

There are 4 best solutions below

0
Michael Lloyd Lee mlk On BEST ANSWER
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.

0
Solorad On

For your task you could use code as bellow:

String t = "[{\"user_id\": \"someValue\"}]";
JSONParser parser = new JSONParser();
JSONArray obj = (JSONArray) parser.parse(t);

System.out.println(obj.get(0));

And result would be JSONObject.

0
Vikrant Kashyap On
String actualJsonObject = // assuming that this variable contains actual object what ever u want to pass as per your question says

JSONParser parser = new JSONParser();
JSONArray userdataArray= (JSONArray) parser.parse(actualJsonObject );
if(userdataArray.size()>0){
     for (Object user : userdataArray) {            
         JSONObject jsonrow=(JSONObject)parser.parse(String.valueOf(user));
         String User_Id= (String)jsonrow.get("user_Id"); \\ Each User_Id will be displayed.
 } else{
       System.out.println("Empty Array....");
    }
0
svichkar On

It works for me.

    String jsonString = "[{\"user_id\": \"someValue\"}]";
    JSONArray jsonArray = new JSONArray();
    JSONParser parser = new JSONParser();
    try {
        jsonArray = (JSONArray) parser.parse(js);
    } catch (ParseException e) {
        e.printStackTrace();
    }