if my JSON file is like this:
{"result":[{"sentence": "Chinese government cafes people cafe crackdown", "id": 1, "txtfile": "002.txt"}, {"sentence": "kalf alo ldk alf", "id": 2, "txtfile": "003.txt"}]}
How to read .json file into java and parser the JSON to get the sentence, id, txtfile ? since my json consists both JSONARRAY AND JSONOBJECT.
private static String jsonFile="D:\\MYJSON.json";
public static void main(String[] args){
JSONParser parser = new JSONParser();
try{
Object obj=parser.parse(new FileReader(jsonFile));
JSONObject jsonObject = (JSONObject) obj;
String sentence=(String) jsonObject.get("sentence");
System.out.println(sentence);
} catch (Exception e){
e.printStackTrace();
}
}
}
I have the error as:java.lang.ClassCastException: java.lang.String cannot be cast to org.json.JSONObject at yyym.ttt.main(ttt.java:46)
This is my JSON
"{\"result\":[{\"sentence\": \"said Chinese government cafes people cafe crackdown\", \"id\": 1, \"txtfile\": \"002.txt\"}, {\"sentence\": \"kalf alo ldk alf\", \"id\": 2, \"txtfile\": \"003.txt\"}]}"
I checked my JSON file is valid. however, When I print it out. It start with " , how to solve the problem?
the output is "{\"result\":[{\"sentence\": \"said Chinese government cafes people cafe crackdown\", \"id\": 1, \"txtfile\": \"002.txt\"}, {\"sentence\": \"kalf alo ldk alf\", \"id\": 2, \"txtfile\": \"003.txt\"}]}"
org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
at org.json.JSONTokener.syntaxError(JSONTokener.java:451)
at org.json.JSONObject.<init>(JSONObject.java:195)
at org.json.JSONObject.<init>(JSONObject.java:319)
at yyym.ttt.main(ttt.java:26)

JSONParser. Looks like something wrong in your file or your method to parse it