2

I would like to read and print the values of a specific id. For example, I would like to read and print the name and the status of the sensor with id = 1. How can I do this using JAVA and JSON file? Could anybody help me?

{
    "Sensor": [
          {
           "id": 1,
           "name": "RR",
           "status": 1,
           },
          {
           "id": 2,
           "name": "RS",
           "status": 1,
           },
          {
           "id": 3,
           "name": "GR",
           "status": 0,
          },

        ],
}

JAVA code to read JSON file :

public class JSON {

    private static String jsonFile = "/Users/foteini/Desktop/JSON/sensor copy.json";   

    public static void main(String[] args) throws FileNotFoundException, IOException, ParseException {

       FileReader reader = new FileReader(jsonFile);

       JSONObject jsonObject = (JSONObject) new JSONParser().parse(reader);

       JSONArray sensors = (JSONArray) jsonObject.get("Sensor");
       //take the elements of the json array
       int id_num=0;
       for (int i=0; i<sensors.size(); i++){
           System.out.println("The sensors in the array:" + sensors.get(i) + "\n");

       }
   }
  }

Thanks a lot for your help!

Pavneet_Singh
  • 36,884
  • 5
  • 53
  • 68
fay
  • 49
  • 1
  • 7
  • Possible duplicate of [How to parse JSON in Java](http://stackoverflow.com/questions/2591098/how-to-parse-json-in-java) – AxelH Dec 02 '16 at 13:42

2 Answers2

2

Your sensor is a JSONArray not a JSONObject so

1.) Fetch your array

2.) Traverse array using indexes and fetch object from array

3.) Fetch values from objects

   JSONObject jsonObject = (JSONObject) new JSONParser().parse(reader);

   // fetch sensor array
   JSONArray sensors = jsonObject.getJSONArray("Sensor");
   JSONObject temp;
   //take the elements of the json array
   int  id ;
   String name,status;

   for (int i=0; i<sensors.size(); i++){
       // fetch array using index
       temp = sensors.getJSONObject(i); 

       // fetch your data
       id = temp.optInt("id");

       if( id==1){
           name   = temp.optString("name");
           status = temp.optString("status");
           System.out.println( name +" "+status);
       }
   }
Pavneet_Singh
  • 36,884
  • 5
  • 53
  • 68
  • Thanks for your reply! But i've get some errors, like "cannot find symbol symbol: method getJSONArray(String) location: variable jsonObject of type JSONObject", "cannot find symbol symbol: method getJSONObject(int) location: variable sensors of type JSONArray", similar errors for optInt, optString. I'm using import org.json.simple. Have you any idea why do i get these errors? – fay Dec 05 '16 at 10:07
  • @foteinikk you have to download and attach `json.org` library as a dependency to your project [follow this link to do it](http://stackoverflow.com/questions/5698900/add-json-package-reference-new-to-java) – Pavneet_Singh Dec 05 '16 at 13:01
1
public class JSON {

/**
 * @param args the command line arguments
 */

private static String jsonFile = "/Users/foteini/Desktop/JSON/sensor copy.json";   

public static void main(String[] args) throws FileNotFoundException, IOException, ParseException {

    FileReader reader = new FileReader(jsonFile);

    JSONObject jsonObject = (JSONObject) new JSONParser().parse(reader);

    JSONArray sensors = (JSONArray) jsonObject.get("Sensor");
    //take the elements of the json array
    int id_num=0;
    for (int i=0; i<sensors.size(); i++){
        JSONObject item = sensors.get(i);
        if (item.getInt("id") == 1){
            // process the item
            System.out.println(item.getString("status"));
        }

     }
   }
}

You have to specify condition int the loop:

Andrii Abramov
  • 10,019
  • 9
  • 74
  • 96
  • Thanks for your reply!! I tried your answer but i've get two errors at getInt and getString. The error is that "cannot find symbol symbol: method getInt(String) location: variable item of type JSONObject" and similar error is for the getString. Have you any idea why do i get these errors? I'm using import org.json.simple. – fay Dec 05 '16 at 10:16
  • @foteinikk in this case replace such methods with explicit casts. `(Integer) item.get("id")` and `(String) item.get("status")`. Here is nice example: https://www.mkyong.com/java/json-simple-example-read-and-write-json/ – Andrii Abramov Dec 05 '16 at 10:29
  • I replaced that as you said but now when i run the code prints out only the first sensor record and then i take an error/exception. The output looks like "The sensors in the array:{"id":0,"status":1,"link":"\/s00\/","name":"RR"} Exception in thread "main" java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer at json.JSON.main at json.JSON.main(JSON.java:49) Java Result: 1". – fay Dec 05 '16 at 11:05