0

I am trying to parse json and running into a small problem.

my json string looks like this:

String json =
    [
        "{caption=blah, url=/storage/emulated/0/DCIM/Camera/20140331_164648.jpg}",
        "{caption=adsf, url=/storage/emulated/0/DCIM/Camera/20140330_103412.jpg}"
    ]

and my code so far looks like this:

try {
JSONArray jsonObj = new JSONArray(json);

for (int i = 0; i < jsonObj.length(); i++) {
    JSONObject c = jsonObj.getJSONObject(i);



    String img = c.getString("url");
    String cap = c.getString("caption");

But its throwing an exception type java.lang.String cannot be converted to JSONObject

What am I doing wrong?

EDIT

If its helpful to anyone, I ended up using GSON to get my json in the correct expected format like this:

Gson gson = new Gson();
String json = gson.toJson(mylist);
7
  • 1
    You used the line getJSONObject but you aren't trying to get a JSONObject, you are trying to get a String. Commented Apr 9, 2014 at 16:01
  • The jSON string is not properly of JSON format Commented Apr 9, 2014 at 16:06
  • try jsonlint.com to test your JSON Commented Apr 9, 2014 at 16:08
  • may you want your json to look like [{"caption": "blah","url": "/storage/emulated/0/DCIM/Camera/20140331_164648.jpg"} Commented Apr 9, 2014 at 16:09
  • @FaisalAli I did, Its valid as a whole but as Sotirios states below its just not in the format I expected Commented Apr 9, 2014 at 16:09

1 Answer 1

3

Your JSON array contains elements like

"{caption=blah, url=/storage/emulated/0/DCIM/Camera/20140331_164648.jpg}"

which is a String not a JSON object. You can't therefore try to retrieve it as a JSONObject.

Seems like you're getting JSON that isn't in the format you expected. Even if you got rid of the "" around it, it still wouldn't be valid JSON, so I don't understand its purpose enough to help you.

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

2 Comments

Is there a better way to convert an arraylist like this ` public ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>(); ` to a json string with objects?
@BluGeni That Java object maps well to JSON like [{"":""}, ...]. In other words a JSON array that contains JSON objects. Each JSON object is a name-value pair of Strings.

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.