我正在使用放心的java,并且我正在使用post请求以获得响应。从我的代码中,我能够获得响应,并且我看到作为响应,我看到我想要存储的值存在于键集中。 这是示例:
{
"status_code": 200,
"status_message": "OK",
"response": {
"applications": {
"345": "A",
"125": "B",
"458": "C",
"434": "D",
"512": "E",
"645": "F"
}
}
}
在上面的示例中,我使用 Json 路径来解析表达式,并且我想使用值“A”从中提取 key (“345”)。
JsonPath js = new JsonPath(res);
String Key = js.get("response.applications.A");
当我使用上面的代码时,它会抛出错误,但是当我运行下面的代码时。
JsonPath js = new JsonPath(res);
String Key = js.get("response.applications.345");
我得到的输出为A。 我知道 [A,b,c,d,e,f] 是什么,但我不知道 [A,b,c,d,e,f] 的 Key 是什么
有没有什么方法可以让我放心地存储该值并打印该值的 key 或用Java以任何其他方式??????
最佳答案
使用JsonPath
,您可以通过调用getMap
来获取 key 。以下是您将如何执行此操作的示例:
String jsonString = "{\"status_code\": 200,\"status_message\": \"OK\",\"response\":{\"applications\":{\"345\": \"A\",\"125\": \"B\",\"458\": \"C\",\"434\": \"D\",\"512\": \"E\",\"645\": \"F\"}}}";
JsonPath jsonPath = new JsonPath(jsonString);
Map<String, String> applicationsMap = jsonPath.getMap("response.applications");
Set<String> applicationKeys = applicationsMap.keySet();
for(String key:applicationKeys){
System.out.println("Key value: " + key + ", Element value: " + applicationsMap.get(key));
}
希望这有帮助!
关于java - 如何在放心的java中从值中找到键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48833235/