【发布时间】:2023-04-03 08:34:01
【问题描述】:
我正在编写一个函数,它在给定坐标的 json 中导航。例如:
{
"a": {
"b" : "c"
},
"d": {
...
}
}
如果我打电话
NavigateThroughJson("a.b", myJsonObject)
我应该得到"c" 作为输出。我这样做是因为我不能使用反序列化,json 具有任意格式。这是我的功能:
public JsonValue NavigateThroughJson(String coordinates, JsonObject jsonObject) {
JsonObject o = jsonObject;
String[] nodes = coordinates.split("\\.");//Splits the dot
for (String node: nodes) {
node = node.replace("\"", ""); //Removes "" from the keys
o = o.getJsonObject(node);
}
return o;
}
问题是,当我为以下 json 尝试此操作时(并调用 NavigateThroughJson("high", jsonAbove)):
{"high":7999.0,"vol":1261.83821469,"buy":7826.01,"last":7884.0,...}
什么都没有返回,就像o.getJsonObject(...)什么都没有返回,甚至null都没有。
我认为这是因为“high”指向一个数字而不是真正的 json 对象,如 high: {...},即使一致的库应该返回 7999.0 作为带有 Type Number 的 JsonObject。可以看到,JsonObject实现了JsonValue,可以有String、Number等类型。见:https://docs.oracle.com/javaee/7/api/javax/json/JsonValue.html
但是,由于 jsonObject 也实现了Map<String, JsonValue>,例如,当我执行map.get("high") 时,我可以获得数字,但我认为这不是正确的方法,如果“high”指向另一个JsonValue 不是 Number(例如,它是一个 json 块 {}),那么我需要将此 JsonValue 视为 Map<String, JsonValue>,但强制转换不是最好的选择。
更新:
这个库似乎有一个错误。请记住,json键是带有“”的字符串,所以如果我尝试:
System.out.println(jsonObject.getJsonObject("high"));
System.out.println("hello?");
它不会打印任何东西,甚至上面的"hello?" 也不会打印!!!但是,如果我这样做:
System.out.println(jsonObject.getJsonObject("\"high\""));
System.out.println("hello?");
"hello?" 已打印,但上面的打印是 "null",尽管我确定密钥 "high"(带有“”)存在,因为我打印了 @987654350 @之前。
【问题讨论】:
-
另外,有没有人知道如何在没有“”键的情况下读取 json?
标签: java json inheritance jsonp