簡體   English   中英

如何從 json 文件中讀取所有 JSON 對象? 爪哇

[英]How to read all JSON objects from json file? Java

當我嘗試從 Json 文件中讀取對象時 - 它只遍歷一個對象 4 次。

public static void main(String[] args) throws Exception {

        String file = "src/main/resources/ip.json";
        String json = readFileAsString(file);
        JSONObject jo = new JSONObject(json);
       
        HashMap result = new ObjectMapper().readValue(json, HashMap.class);
        
            for (Object entry : result.keySet()) {

                String id = (String) jo.get().get("id");
                System.out.println(id);
                String ip = (String) jo.get("ip");
                System.out.println(ip);
                Integer score = (Integer) jo.get("score");
                System.out.println(score);

            }

        }

        public static String readFileAsString (String file) throws IOException {
            return new String(Files.readAllBytes(Paths.get(file)));
        }

    }

-------------------------------------Json 文件------------ --------------------

{
  "id": "test",
  "score": 12,
  "ip": "1.2.3.4",
  "message": "Hi"
},
{
"id": "test",
"score": 5,
"ip": "1.2.3.5"
},
{
"id": "test",
"score": 17,
"ip": "1.2.3.4"
},
{
"id": "test2",
"score": 9,
"ip": "1.2.3.4"
}

輸出:

測試 1.2.3.4 12 測試 1.2.3.4 12 測試 1.2.3.4 12 測試 1.2.3.4 12

如果你想讀取多個 json 對象,它們應該在一個 JSON 數組中。 例如,

[{"id": "test", "score": 12, "ip": "1.2.3.4", "message": "Hi" }, { "id": "test", "score": 5, "ip": "1.2.3.5" }, { "id": "test", "score": 17, "ip": "1.2.3.4" }, { "id": "test2", "score": 9, "ip": "1.2.3.4" }]

請參考這里的類似問題。

您的 Json 文件沒有 json 數組,只有一個對象。 數組是這樣的。

[
 {
   "id": "test",
   "score": 12,
   "ip": "1.2.3.4",
   "message": "Hi"
 },
 {
  "id": "test",
  "score": 5,
  "ip": "1.2.3.5"
 },
 {
  "id": "test",
  "score": 17,
  "ip": "1.2.3.4"
 },
 {
  "id": "test2",
  "score": 9,
  "ip": "1.2.3.4"
 }
]

所以像上面一樣編輯你的 Json 文件並嘗試這個。

public static void main(String[] args) throws Exception {

        String file = "src/main/resources/ip.json";
        String json = readFileAsString(file);
        JSONArray jsonArray = new JSONArray(json);
        for(int i=0; i < jsonArr.length();i++){
            JSONObject jo = jsonArr.getJSONObject(i);       
            HashMap result = new ObjectMapper().readValue(jo, HashMap.class);
        
            for (Object entry : result.keySet()) {

                String id = (String) jo.get().get("id");
                System.out.println(id);
                String ip = (String) jo.get("ip");
                System.out.println(ip);
                Integer score = (Integer) jo.get("score");
                System.out.println(score);

            }

        }

        public static String readFileAsString (String file) throws IOException {
            return new String(Files.readAllBytes(Paths.get(file)));
        }

    }

暫無
暫無

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

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