Query a JSONObject in java

后端 未结 6 1718
鱼传尺愫
鱼传尺愫 2020-11-27 06:12

I was wondering if somewhere out there exists a java library able to query a JSONObject. In more depth I\'m looking for something like:



        
6条回答
  •  佛祖请我去吃肉
    2020-11-27 07:14

    Using Java JSON API 1.1.x (javax.json) one can make use of new JavaPointer interface. Instance implementing this interface can be considered to some extend as kind of XPath expression analog (see RFC-6901 for details). So in your case you could write this:

    import javax.json.*;
    //...
    var jp = Json.createPointer("/data/data2/value");
    System.out.println(jp.getValue(jsonObject));
    

    In 1.1.4 version of JSON there's also nice addition to JsonStructure interface (which is implemented by JsonObject and JsonArray), namely getValue(String jsonPointer). So it all comes down to this simple one-liner:

    System.out.println(jsonObject.getValue("/data/data2/value"));
    

提交回复
热议问题