简体   繁体   English

使用JXPathContext / java通过Xpath解析json对象

[英]Parsing a json Object by Xpath using JXPathContext/java

I want to parse a json object by xpath in java.I have tried in the following way: 我想通过java中的xpath解析一个json对象,我尝试了以下方式:

  JSONObject obj=new JSONObject("{\\"firstName\\":\\"John\\",\\"lastName\\":\\"doe\\",\\"age\\":26,\\"address\\":{\\"streetAddress\\":\\"naiststreet\\",\\"city\\":\\"Nara\\",\\"postalCode\\":\\"630-0192\\"},\\"phoneNumbers\\":[{\\"type\\":\\"iPhone\\",\\"number\\":\\"0123-4567-8888\\"},{\\"type\\":\\"home\\",\\"number\\":\\"0123-4567-8910\\"}]}"); JXPathContext context = JXPathContext .newContext(obj); Iterator i=context.iterate("phoneNumbers[0]/type"); 

But i found out that the above way is not working as the Iterator doesnt contain anything. 但是我发现上述方法不起作用,因为Iterator不包含任何内容。 Can anyone please let me know whether I am doing any mistake here? 有人可以让我知道我在这里做错什么吗? Also,can anyone please let me know if there is any other better way of parsing a json object by xpath. 另外,有人可以让我知道是否还有其他更好的方法可以通过xpath解析json对象。

As highlighted in comment, the XPath is wrong due to indexes starting with 1. 如注释中突出显示,由于索引从1开始,XPath是错误的。

The second trick is to call "toMap" on your JSONObject. 第二个技巧是在JSONObject上调用“ toMap”。 JXPath doesn't know how to deal with JSONObject, but can deal with maps. JXPath不知道如何处理JSONObject,但是可以处理地图。

JSONObject  obj=new JSONObject("{\"firstName\":\"John\",\"lastName\":\"doe\",\"age\":26,\"address\":{\"streetAddress\":\"naiststreet\",\"city\":\"Nara\",\"postalCode\":\"630-0192\"},\"phoneNumbers\":[{\"type\":\"iPhone\",\"number\":\"0123-4567-8888\"},{\"type\":\"home\",\"number\":\"0123-4567-8910\"}]}");

JXPathContext context = JXPathContext .newContext(obj.toMap());
Iterator i=context.iterate("phoneNumbers[1]/type");

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

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