0

I am trying to parse a JSON response in Java but am facing difficulty due to the response being array format, not object. I, first, referenced the this link but couldn't find a solution for parsing the JSON properly. Instead, I am receiving this error when trying to display the parsed data...

Exception in thread "main" org.json.JSONException: JSONObject["cardBackId"] not found.

Snippet for displaying data:

JSONObject obj = new JSONObject(response);
JSONArray cardBackId = (JSONArray) obj.get("cardBackId");
System.out.println(cardBackId);

Data response via Postman:

[
    {
        "cardBackId": "0",
        "name": "Classic",
        "description": "The only card back you'll ever need.",
        "source": "startup",
        "sourceDescription": "Default",
        "enabled": true,
        "img": "http://wow.zamimg.com/images/hearthstone/backs/original/Card_Back_Default.png",
        "imgAnimated": "http://wow.zamimg.com/images/hearthstone/backs/animated/Card_Back_Default.gif",
        "sortCategory": "1",
        "sortOrder": "1",
        "locale": "enUS"
    },

While without JSONObject I am pulling the data fine in Java and verified by using response.toString in STDOUT, this is my first time using json library in Java and it is important I parse this data as json. Any advice with this is helpful.

3 Answers 3

1

The response is an array and not object itself, try this:

JSONObject obj = new JSONArray(response).getJSONObject(0);
String cardBackId = obj.getString("cardBackId");

Here is the output, along with relevant files used: enter image description here

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

3 Comments

When trying this response, I receive this error -> Exception in thread "main" org.json.JSONException: JSONArray initial value should be a string or collection or array.
I tried your new response and received the same error.. Exception in thread "main" org.json.JSONException: JSONArray initial value should be a string or collection or array.
Worked. I needed to do JSONObect obj = new JSONArray(response.toString()).getJSONObject(0); I was missing the toString
0
  1. First parse the response as JsonArray, instead of JsonObject.
  2. Get JsonObject by iterating through the array.
  3. Now get the value using the key.

1 Comment

I tried that a bit ago but am receiving this error : Exception in thread "main" org.json.JSONException: JSONArray initial value should be a string or collection or array. This is the code i'm using that is giving me error: JSONArray arr = new JSONArray(response); for(int i = 0; i < arr.length(); i++){ JSONObject obj = arr.getJSONObject(i); String name = obj.getString("name"); System.out.println(name.toString()); }
0

Look at this example using Gson library, where you need to define the Datatype to define how to parse the JSON.

The key part of the example is: Data[] data = gson.fromJson(json, Data[].class);

package foo.bar;
import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;

public class Main {

    private class Data {
        long cardBackId;
        String name;
    }

    public static void main(String[] args) throws FileNotFoundException {
        // reading the data from a file
        BufferedReader reader = new BufferedReader(new FileReader("data.json"));
        StringBuffer buffer = new StringBuffer();
        reader.lines().forEach(line -> buffer.append(line));
        String json = buffer.toString();

        // parse the json array
        Gson gson = new Gson();
        Data[] data = gson.fromJson(json, Data[].class);

        for (Data item : data) {
            System.out.println("data=" + item.name);
        }

    }

}

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.