簡體   English   中英

通過使用JAVA提供特定的id - JSON文件來獲取特定值

[英]Get specific values by giving specific id - JSON file using JAVA

我想閱讀並打印特定id的值。 例如,我想讀取並打印id = 1sensornamestatus 如何使用JAVAJSON文件執行此操作? 有人能幫助我嗎?

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

        ],
}

用於讀取JSON文件的JAVA代碼:

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");

       }
   }
  }

非常感謝你的幫助!

您的sensorJSONArray而不是JSONObject

1.)獲取你的數組

2.)使用索引遍歷數組並從數組中獲取對象

3.)從對象中獲取值

   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);
       }
   }
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"));
        }

     }
   }
}

你必須在循環中指定condition:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM