0

I'm trying to parse the json format:

 {"data":["Laptop","Desktop","Ultrabook"]}

but this seems to give me an error:

 JSONArray jr = new JSONArray(jsonStr);

I tried to parse the strings instead, but i doubt thats the best practice. And, I couldn't figure out how to parse the quotations out of the string.

5 Answers 5

2

Change this

JSONArray jr = new JSONArray(jsonStr);

to

JSONObject jsonobject = new JSONObject(jsonStr);

Then

JSONArray jr = jsonobject.getJSOnArray("data");
for(int i=0;i<jr.length();i++)
{
  String value =(String) jr.get(i);
}

Your json

{ // json object node
    "data": [ // json array data
        "Laptop",
        "Desktop",
        "Ultrabook"
    ]
}
Sign up to request clarification or add additional context in comments.

Comments

1

That's because you are not getting a JSONArray but JSONObject (the root element is not an array). Try this:

JSONObject data = new JSONObject(jsonStr).getJSONArray("data");

Comments

1

do :

JSONObject obj = new JSONObject(jsonStr);

JSONArray arr =  obj.getJSONArray("data");

Comments

1

your first tag in JSONObject not a JSONArray.

So you need to change this from

JSONArray jr = new JSONArray(jsonStr);

to

JSONObject jObject = new JSONObject(jsonStr);

Comments

0

try like this

    String data = "{\"data\":[\"Laptop\",\"Desktop\",\"Ultrabook\"]}";

    try {
        JSONObject jObj = new JSONObject(data);
        JSONArray jsonArray = new JSONArray();
        jsonArray= jObj.optJSONArray("data");

        for (int i = 0; i < jsonArray.length(); i++) {

            System.out.println(jsonArray.get(i).toString());

        }
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        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.