0

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)

enter image description here

4
  • i think this is what you want : stackoverflow.com/questions/2591098/how-to-parse-json-in-java Commented Oct 7, 2016 at 8:50
  • IN MY CASE, my objective is inside JSONARRAY , how to parse Commented Oct 7, 2016 at 8:57
  • Post code of JSONParser. Looks like something wrong in your file or your method to parse it Commented Oct 7, 2016 at 9:16
  • @HiPownedBi Which jar you are using for json?? and json parser?? Commented Oct 7, 2016 at 10:28

5 Answers 5

2

Result is an array, first you have to get that array, loop over that array and then get the desired json objects.

Library used in the following code is - org.json

Code

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class Example {

    public static void main(String[] args) {

        //String jsonString = "{\"result\":[{\"sentence\": \"Chinese government cafes people cafe crackdown\", \"id\": 1, \"txtfile\": \"002.txt\"}, {\"sentence\": \"kalf alo ldk alf\", \"id\": 2, \"txtfile\": \"003.txt\"}]}";

        String jsonString = readJsonFile("filePath");

        try {
            JSONObject jsonObject = new JSONObject(jsonString);
            JSONArray result = jsonObject.getJSONArray("result");
            for (int i =0; i < result.length(); i++){
                JSONObject j = result.getJSONObject(i);
                String s = j.getString("sentence");
                int id = j.getInt("id");
                String txtFile = j.getString("txtfile");
                System.out.println("Sentence is " + s);
                System.out.println("Id is " + id);
                System.out.println("text file is " + txtFile);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public static String readJsonFile(String filePath) {
    String jsonData = "";
    BufferedReader br = null;
    try {
        String line;
        br = new BufferedReader(new FileReader(filePath));
        while ((line = br.readLine()) != null) {
            jsonData += line + "\n";
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (br != null) {
                br.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    return jsonData;
}
}

Output

  1. Sentence is Chinese government cafes people cafe crackdown.
  2. Id is 1
  3. text file is 002.txt
  4. Sentence is kalf alo ldk alf
  5. Id is 2
  6. text file is 003.txt
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks. it works. However, I would like to get the JSON content from my json file. The issue might be dut to " Object obj=parser.parse(new FileReader(jsonFile)); " as I have this error: java.lang.ClassCastException: java.lang.String cannot be cast to org.json.JSONObject at yyym.ttt.main(ttt.java:41) . May I know where I did wrong?
@HiPownedBi You can read your json text file to get the desired json String. Did you check whether the json text in the file is a valid json?
Thanks a lot. I am sorry to bother u again. why I get this error: A JSONObject text must begin with '{' at 1 [character 2 line 1] . I check my JSON content with your //String jsonString = "{\"result\":[{\"sentence\": \"Chinese government cafes people cafe crackdown\", \"id\": 1, \"txtfile\": \"002.txt\"}, {\"sentence\": \"kalf alo ldk alf\", \"id\": 2, \"txtfile\": \"003.txt\"}]}"; They are the same. Why I read the .json file get the above error
@HiPownedBi In simple terms the error says your json is not valid. Check you json here - Jsonlint
@HiPownedBi How you are assigning your json to the string? for ex are you doing it like this String json = ""\{\""?
|
1

I am using this jars file: jsonsimple.jar

http://www.java2s.com/Code/Jar/j/Downloadjsonsimplejar.htm

 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;
            System.out.println("KK:"+jsonObject.toString());
            JSONArray jarray = (JSONArray) jsonObject.get("result");
            for (int i=0;i<jarray.size();i++) {
                jsonObject = (JSONObject) jarray.get(i);
                String sentence = (String)jsonObject.get("sentence"); 
             System.out.println(sentence);
            }

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

Output:

{"result":[{"sentence":"Chinese government cafes people cafe crackdown","txtfile":"002.txt","id":1},{"sentence":"kalf alo ldk alf","txtfile":"003.txt","id":2}]}
Chinese government cafes people cafe crackdown
kalf alo ldk alf

2 Comments

I do not know why i get this error by using your code. java.lang.ClassCastException: java.lang.String cannot be cast to org.json.simple.JSONObject
@HiPownedBi use these import : import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser;
0

result is JsonArray, and you can loop over it to get JsonObjects e.g:

Object obj=parser.parse(new FileReader(jsonFile));  
JSONObject jsonObject = (JSONObject) obj;
JSONArray values = item.json.optJSONArray("result");
JSONObject json;
String sentence = "";
//loop to get object
for (int i = 0; i < values.length(); i++){
    json = values.getJSONObject(i);
    //get sentenence
    sentence = json.getString("sentence");
}

Comments

0
 String sentence=null;
    JSONArray jsonArray = jsonObject.getJSONArray("result");
    if(jsonArray.length()>0){
     for(int i=0;i<jsonArray.length();i++){
        JSONObject jo=jsonArray.getJSONObject(i);
        sentence=jo.getString("sentence");
       }
   }

1 Comment

I still have this error: java.lang.ClassCastException: java.lang.String cannot be cast to org.json.JSONObject at yyym.ttt.main(ttt.java:41)
0

Use instanceof to check whether that data is JsonObject or JsonArray

Sample code given below

public void main() {
    String jsonFile = "D:\\MYJSON.json";
    JSONParser parser = new JSONParser();
    try {
        Object obj = parser.parse(new FileReader(jsonFile));
        if (obj instanceof JSONObject) {
            JSONObject jsonObject = (JSONObject) obj;
            String sentence = jsonObject.optString("sentence");
            System.out.println(sentence);
        } else if (obj instanceof JSONArray) {
            JSONArray jsonArray = (JSONArray) obj;
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObj = jsonArray.getJSONObject(i);
                String sentence = jsonObj.optString("sentence");
                System.out.println(sentence);
            }//end of for loop
        }//end of else if
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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.