16

I have this JSON coming from one of our REST service:

[
    "{\"category_name\":[\"Industry Components\"],\"categoryId\":[1]}",
    "{\"category_name\":[\"Business Components\"],\"categoryId\":[2]}",
    "{\"category_name\":[\"Utilities\"],\"categoryId\":[3]}",
    "{\"category_name\":[\"Tools\"],\"categoryId\":[4]}
]

I am using java-json.jar to parse this JSON, this is the simple snippet where I am trying to pass above JSON string:

JSONObject jsonObject = new JSONObject(jsonStr);

But I am getting below exception:

org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]

First I assumed it's because of [ and ] characters in JSON and I tried to replace as below:

String replacedStr = jsonStr.replaceAll("\\[", "").replaceAll("\\]", "")

But even then I am getting same exception. Can anyone please guide me to know what I am doing wrong?

1
  • 1
    Looks like you're missing a closing quote on the last line. Commented Oct 16, 2013 at 9:04

4 Answers 4

37

I suppose that you should use not JSONObject, but JSONArray

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

Comments

14

JSON Object follows the following Structure:

{
 "array": [
{
    color: "red",
    value: "#f00"
},
{
    color: "green",
    value: "#0f0"
}
]
}

JSON Array follows the following Structure:

[
 { "firstName":"John" , "lastName":"Doe" }, 
 { "firstName":"Anna" , "lastName":"Smith" }, 
 { "firstName":"Peter" , "lastName": "Jones" }
]

2 Comments

If you're going to embed an array in an object it needs to look like { "key": [ value(s) ] }
Also I don't have control on the input (ie JSON) which I am receiving. (And I didn't downvote you)
1

instead

JSONObject jsonObject = new JSONObject(jsonStr);

use

JSONArray jsonArray = new JSONArray(jsonStr);

and may be read about Gson is a nice library for parsing and work with json

Comments

0

If you get JSONObject text must begin with '{' exception. Then first off all check what did u pass to the JSONObject constructor.

You should pass the right json.txt file.So make sure what are u passing to jsonobject.

String request = FileUtils.readFileToString(new File("/home/achaure/Downloads/Amol/KountRestTest/Documents/request.txt"));

JSONObject jsonObject = new JSONObject(request);

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.