简体   繁体   中英

Parsing all JSONObject in JSON file using java

My purpose is to parse twitter data which is described in JSON file. I created a void for parsing JSON which function perfectly, but it show me only one JSONObject while my `

public void parsingJson( String d) throws Exception
      {

    BufferedReader br = null;
    //JSONObject rootObejct=null;
    JSONObject js=new JSONObject();

    try {

        String sCurrentLine;
        InputStream inputStream = new FileInputStream("E://inputdata.json") ;
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        br = new BufferedReader(inputStreamReader);

         while ((sCurrentLine = br.readLine())!= null) {
             JSONObject rootObejct=new JSONObject(sCurrentLine);


             for(@SuppressWarnings("unchecked")
            Iterator<String> iter = rootObejct.keys();iter.hasNext();) {
                    String key = iter.next();

                    try {
                        if (key.startsWith(d)){
                        System.out.println("******key*********"+key);
                        Object value = rootObejct.get(key);
                        System.out.println("keys vlaue "+value.toString());
                        }
                    } catch (JSONException e) {
                        // Something went wrong!
                    }

             }
          }

`

Here's a simple code to read a JSON file

public void readJSONFile(String filePath) {
    try {
    JSONParser parser = new JSONParser();
    Object obj = parser.parse(new FileReader(filePath));

    JSONObject jsonObject =  (JSONObject) obj;

    //if your value is an array
    JSONArray arr = (JSONArray) jsonObject.get("array");
    //if your value is string
    String str = (String) jsonObject.get("status");

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

}

JSON file used as test case is

    {
      "status": "OK",
      "array": [ "Hello" ]
    }

If it doesn't help, please let me know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM