首页 > 解决方案 > 如何从 json 文件中读取所有 JSON 对象?爪哇

问题描述

当我尝试从 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

标签: javajson

解决方案


Your Json file does not have a json array, only an objects. Array is something like this.

[
 {
   "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"
 }
]

So edit your Json file like above and try this.

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);       
            System.out.println(jo.getString("id"));
            System.out.println(jo.getString("ip"));
            System.out.println(jo.getInt("score"));
        }

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

    }

推荐阅读