2

It's my first time working with a JSON file, so I went with simple JSON library. Here's what works:

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class ParseCardJSON {

    public static void main(String[] args) {

        JSONParser parser = new JSONParser();

        Object obj;

        try {
          obj = parser.parse(new FileReader("C:\\Users\\owner\\Desktop\\A\\programming\\workspace\\MTG\\AllSets.json"));
          JSONObject jsonObject = (JSONObject) obj;
          System.out.println(obj.toString());
          String name = (String) jsonObject.get("name");
          String color = (String) jsonObject.get("power");
          System.out.println("Name: " + name);
          System.out.println("color: " + color);

        } catch (Exception e) {
          e.printStackTrace();
        }
    }
}

So the System.out.println(obj.toString()); prints out what I'm expecting:

({"LEA":{"name":"Limited Edition Alpha","code":"LEA","gathererCode":"1E","magicCardsInfoCode":"al","releaseDate":"1993-08-05","..)...

but the "name" and "color" prinlns are null. Any idea what could be wrong?

0

1 Answer 1

3

This happen because the name property is not in the root.

In fact you have a LEA key that is in the root, and the value of that property is another Object, that contains the following keys : name, code, gathererCode, magicCardsInfoCode, etc...

So if you want extract the name property, you need to do something like this

JSONObject object = (JSONObject) jsonObject.get("LEA");
String name = (String) object.get("name");

This should fix the problem.

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

4 Comments

Appreciate it. So if I'm understanding, the entire JSON object is wrapped in a key, so I need to let my parser know that so that it delves beyond just the top level? Unfortuntely, jsonObject.get is throwing an error for me though (Cannot make a static reference to the non-static method get(Object) from the type HashMap). Any idea how to fix this? Removing the static in a main isn't really an option, right?
Could you provide the code please? I'll show you the fix.
Looks like it's working now, so it must have been something little I was doing. Thanks for the help!
No problem. My pleasure

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.