3

I am trying to parse a son file, and I don't know what I'm doing wrong (of course, I don't really know what I'm doing right, either).

file.json

[{  
"arrOne":{  
    "one":"a",
    "two":"b",
    "three":"c",
    "four":"d",
    "five":"e"
},
"elemTwo":"f",
"elemThree":"g",
"elemFour":"h",
"elemFive":"i",
"arrSix":[{  
    "six":1,
    "seven":2,
    "eight":"j"
}]}]

code:

import java.io.FileNotFoundException;
import java.io.FileReader;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
//...........
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("/path/to/file.json"));
JSONObject json = (JSONObject) obj;
String unit = (String) json.get("elemTwo");
System.out.println(unit);

I get the error ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject. Truthfully, I have no idea what I'm doing. Any help would be great! Thanks!

1
  • 1
    You've got a JSON array in your data (it's wrapped in []). So, if you parse it, its type is JSONArray, not JSONObject - exactly what the exception says. Commented Jan 29, 2016 at 22:01

3 Answers 3

4

You should cast your obj toJsonArrayinstead of JsonObject, because your json file has [] at the root.

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

Comments

2

you are getting JSONArray not JsonObject

JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("/path/to/file.json"));
JSONArray json = (JSONArray) obj;

Than loop this and get jsonobject

Comments

0

When the JSonParser parses the file, it's returning it as a JSONArray, to solve it try to use this:

    JSONObject obj = (JSONObject)obj;
    JSONObject elem = (JSONObject)obj.get("0");
    String unit = (String) elem.get("elemTwo");
    System.out.println(unit);

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.