SimpleJson: String to JSONArray
Asked Answered
V

4

14

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?

Vitus answered 25/2, 2016 at 9:6 Comment(1)
I think i can help u out. Please post some more info in JSON .. its very little to provide you exact code.. i have done this in my project.. Thank YouCorridor
D
19
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.

Deerdre answered 25/2, 2016 at 9:17 Comment(0)
U
1

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.

Usquebaugh answered 25/2, 2016 at 9:14 Comment(0)
C
0
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....");
    }
Corridor answered 25/2, 2016 at 9:25 Comment(0)
W
0

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();
    }
Weide answered 25/2, 2016 at 9:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.