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?

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 You Commented Feb 25, 2016 at 9:10

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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....");
    }

Comments

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();
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.