Nitesh Suresh
Nitesh Suresh

Reputation: 53

Unable to match node containing forward-slash (/) using jackson library

I am unable to match node using jackson JSONNode#at method if JSON key contains / which is also used as separator in syntax of at method.

For instance in below JSON

{
    "message": "Hi",
    "place/json": {
        "name": "World!"
    }
}

we have key place/json which includes / is part of key.

If I use code like

public static void main(String[] args) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    String jsonHiWorld = "{\"message\":\"Hi\",\"place/json\":{\"name\":\"World!\"}}";
    String message = mapper.readTree(jsonHiWorld).at("/message").asText();
    String place = mapper.readTree(jsonHiWorld).at("/place/json/name").asText();
    System.out.println(message + " " + place); // should print "Hi World!"
}

I am getting as output: Hi
But expectation output is: Hi World

Upvotes: 4

Views: 2102

Answers (1)

Luke Woodward
Luke Woodward

Reputation: 64959

The JSONNode#at method matches nodes in JSON documents using JSON Pointer. To match against the / character in a property name using JSON Pointer, you have to replace the / symbol with ~1.

Try replacing

    String place = mapper.readTree(jsonHiWorld).at("/place/json/name").asText();

with

    String place = mapper.readTree(jsonHiWorld).at("/place~1json/name").asText();

See also the example in section 5 of RFC 6901.

Upvotes: 10

Related Questions