简体   繁体   English

JsonPath - 获取 JSON 中第一个属性的名称 - Java

[英]JsonPath - Get name of the first property in JSON - Java

I am trying to get property name in JSON response object in Java Spring Boot using JsonPath.我试图在 JSON 响应 object 中使用 JD52387880E1EA22817A72D3759213819Z Z38008DD81C2F8D7985ECFZDCE0 获取属性名称。 I want to acces first (or second) property name, but I don´t want to hardcode them.我想访问第一个(或第二个)属性名称,但我不想硬编码它们。

I find out that when I use * wildcard, selecting multiple nodes is not supported.我发现当我使用 * 通配符时,不支持选择多个节点。

JSON format is: JSON 格式为:

{
   "item1": [
     {...},
     {...},
     {...},
    ],
   "item2": [
     {...},
     {...},
     {...},
    ],
}

Do you have any idea, if this is posible?你有什么想法,如果这是可能的?

Thank you谢谢

Yes.是的。 What you want to do is iterate over the keys of the JsonObject你想要做的是遍历 JsonObject 的键

JSONObject jsonObject = new JSONObject(contents.trim());
Iterator<String> keys = jsonObject.keys();

while(keys.hasNext()) {
    String key = keys.next();
    if (jsonObject.get(key) instanceof JSONObject) {
          // do something with jsonObject here      
    }
}

Reference: https://stackoverflow.com/a/10593838/7622687参考: https://stackoverflow.com/a/10593838/7622687

I figured it out - I didn't use response from endpoint.我想通了 - 我没有使用端点的响应。 I used output of the method that was as a endpoint handler.我使用了作为端点处理程序的方法的 output。 And then I used @NiksVij's solution above.然后我在上面使用了@NiksVij 的解决方案。

Thanks!谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM