When I try to read objects from Json file - it only iterate through one object 4 times.
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 File--------------------------------
{
"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"
}
OUTPUT:
test 1.2.3.4 12 test 1.2.3.4 12 test 1.2.3.4 12 test 1.2.3.4 12
CodePudding user response:
If you want to read MULTIPLE json objects, they should be in a JSON array. For example,
[{"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" }]
Please refer to similar question here.
CodePudding user response:
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);
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)));
}
}