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!