Search code examples
javaxmljsonparsingjsonpath

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.

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?

Thanks


Solution

  • I can explain the XPath for you

    //*[1] selects the first element node in the document. This would be the document element and here can be only one so it is a little strange. /* returns the same node.

    //*[1]/* or /*/* return all element child nodes of the document element.

    [local-name()='tagname'] filters nodes by their local name (the tag name without the namespace prefix).

    The full expression //*[1]/*[local-name()='tagname'] fetches all direct child nodes of the document element with the provided tagname, ignoring namespaces. It could be simplified to /*/*[local-name()='tagname'].

    Without knowing the Json, here is no chance to say how the JsonPath should look like. 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).