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?
JSONObject. NULL is equivalent to the value that JavaScript calls null, whilst Java's null is equivalent to the value that JavaScript calls undefined.
A JSONObject is an unordered collection of key and value pairs, resembling Java's native Map implementations. Keys are unique Strings that cannot be null. Values can be anything from a Boolean, Number, String, or JSONArray to even a JSONObject. NULL object.
JSONObject and JSONArray are the two common classes usually available in most of the JSON processing libraries. A JSONObject stores unordered key-value pairs, much like a Java Map implementation. A JSONArray, on the other hand, is an ordered sequence of values much like a List or a Vector in Java.
JsonArray represents an immutable JSON array (an ordered sequence of zero or more values). It also provides an unmodifiable list view of the values in the array. A JsonArray object can be created by reading JSON data from an input source or it can be built from scratch using an array builder object.
I suppose that you should use not JSONObject, but JSONArray
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" }
]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With