简体   繁体   English

为JSON字符串创建Java解析器

[英]Creating java parser for json string

I'm trying to translate a java method that uses Xpath to parse XML to one that uses JsonPath instead and I'm having trouble translating what the Xpath parser is doing so i can replicate it using JsonPath. 我正在尝试将使用Xpath解析XML的Java方法转换为使用JsonPath解析的Java方法,并且在转换Xpath解析器正在执行的操作时遇到问题,因此我可以使用JsonPath复制它。

Here is the code that currently parses "String body". 这是当前解析“字符串主体”的代码。

public static String parseXMLBody(String body, String searchToken) {
    String xPathExpression;
    try {
            // we use xPath to parse the XML formatted response body
        xPathExpression = String.format("//*[1]/*[local-name()='%s']", searchToken);
        XPath xPath = XPathFactory.newInstance().newXPath();
        return (xPath.evaluate(xPathExpression, new InputSource(new StringReader(body))));
    } catch (Exception e) {
            throw new RuntimeException(e); // simple exception handling, please review it
    }
}

Can anyone help translate this into a method that uses JsonPath or something similar? 谁能帮助将其转换为使用JsonPath或类似方法的方法?

Thanks 谢谢

I can explain the XPath for you 我可以为您解释XPath

//*[1] selects the first element node in the document. //*[1]选择文档中的第一个元素节点。 This would be the document element and here can be only one so it is a little strange. 这将是document元素,此处只能是一个,因此有点奇怪。 /* returns the same node. /*返回相同的节点。

//*[1]/* or /*/* return all element child nodes of the document element. //*[1]/*/*/*返回文档元素的所有元素子节点。

[local-name()='tagname'] filters nodes by their local name (the tag name without the namespace prefix). [local-name()='tagname']通过节点的本地名称(没有名称空间前缀的标签名称[local-name()='tagname']过滤节点。

The full expression //*[1]/*[local-name()='tagname'] fetches all direct child nodes of the document element with the provided tagname, ignoring namespaces. 完整表达式//*[1]/*[local-name()='tagname']提取具有提供的标记名的文档元素的所有直接子节点,而忽略名称空间。 It could be simplified to /*/*[local-name()='tagname'] . 可以简化为/*/*[local-name()='tagname']

Without knowing the Json, here is no chance to say how the JsonPath should look like. 不了解Json,就没有机会说说JsonPath的外观。 I would not expect the Json to have a root element, but I expect the items to be different because in Json you can not have multiple siblings with the same key (You can have multiple siblings with the same node name in XML). 我不希望Json具有根元素,但是我希望项目有所不同,因为在Json中,不能有多个具有相同键的兄弟(在XML中可以有具有相同节点名的多个兄弟)。

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

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