Reputation: 83
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" prinln
s are null
. Any idea what could be wrong?
Upvotes: 2
Views: 4622
Reputation: 132
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.
Upvotes: 3