问题描述
[{"id":"939f0080-e93e-4245-80d3-3ac58a4a4335","name":"Micha","date":"2021-04-20T11:21:48.000Z","entry":"Wow"},{"id":"939f0070-e93f-4235-80d3-3ac58a4a4324","name":"Sarah","date":"2021-04-21T11:21:48.000Z","entry":"Hi"},{"id":"897f0080-e93e-4235-80d3-3ac58a4a4324","name":"John","date":"2021-04-25T17:11:48.000Z","entry":"Hi how are you"}...]
我使用 Json-simple 来获取数组,但我只能获取对象,而不能获取值。
JSONParser jsonParser = new JSONParser();
try {
FileReader reader = new FileReader("j.json");
Object object = jsonParser.parse(reader);
JSONArray jsonArray = (JSONArray) object;
//prints the first Object
System.out.println("element 1 is" + jsonArray.get(0));
//prints whole Array
System.out.println(jsonArray);
我如何遍历我的文件并获取每个日期、名称日期和条目而不是对象的值?
我想得到类似的东西:
"id is 939f0080-e93e-4245-80d3-3ac58a4a4335 name is Micha date is 2021-04-20T11:21:48.000Z enry is wow"
"id is 939f0070-e93f-4235-80d3-3ac58a4a4324 name is Sarah 2021-04-21T11:21:48.000Z date is 2021-04-21T11:21:48.000Z"
"name is ..."
解决方法
你想要的基本上是这个
public static void main(String[] args) {
JSONParser jsonParser = new JSONParser();
try (FileReader reader = new FileReader("j.json")) {
Object object = jsonParser.parse(reader);
JSONArray jsonArray = (JSONArray) object;
for (Object o : jsonArray) {
JSONObject jsonObject = (JSONObject) o;
System.out.printf("id is %s name is %s date is %s entry is %s%n",jsonObject.get("id"),jsonObject.get("name"),jsonObject.get("date"),jsonObject.get("entry"));
// Or if you want all
for (Object key : jsonObject.keySet()) {
System.out.printf("%s is %s",key,jsonObject.get(key));
}
System.out.println();
}
} catch (IOException | ParseException e) {
e.printStackTrace();
}
}
如果属性是可选的,您可以使用 getOrDefault
。还有无数其他库可以将您的 json 转换为 java 对象。这会给你更多的类型安全。例如。 jackson
或 gson
。
JSONArray 实现了 Collection 和 Iterable,因此您可以使用 For 循环或使用 Iterator 或 Stream 对其进行迭代。遗憾的是,该对象不是泛型类型的,因此您将始终获得对象并且必须自己强制转换它们:
for(Object value : jsonArray) {
// your code here //
}
,
希望这会有所帮助:
JSONParser jsonParser = new JSONParser();
try {
Object object = jsonParser.parse("[{\"id\":\"939f0080-e93e-4245-80d3-3ac58a4a4335\",\"name\":\"Micha\",\"date\":\"2021-04-20T11:21:48.000Z\",\"entry\":\"Wow\"},{\"id\":\"939f0070-e93f-4235-80d3-3ac58a4a4324\",\"name\":\"Sarah\",\"date\":\"2021-04-21T11:21:48.000Z\",\"entry\":\"Hi\"},{\"id\":\"897f0080-e93e-4235-80d3-3ac58a4a4324\",\"name\":\"John\",\"date\":\"2021-04-25T17:11:48.000Z\",\"entry\":\"Hi how are you\"}]");
JSONArray jsonArray = (JSONArray) object;
jsonArray.forEach(x -> {
JSONObject o = (JSONObject) x;
String collect = o.entrySet()
.stream()
.map(e -> e.getKey() + " is " + e.getValue().toString())
.collect(Collectors.joining(" "));
System.out.println(collect);
});
} catch (ParseException e) {
e.printStackTrace();
}