55

I have the following json:

{"test":"example"}

I use the following code from Faster XML Jackson.

JsonParser jp = factory.createParser("{\"test\":\"example\"}");
json = mapper.readTree(jp);
System.out.println(json.get("test").toString());

It outputs:

"example"

Is there a setting in Jackson to remove the double quotes?

basickarl
  • 37,187
  • 64
  • 214
  • 335

3 Answers3

108

Well, what you obtain when you .get("test") is a JsonNode and it happens to be a TextNode; when you .toString() it, it will return the string representation of that TextNode, which is why you obtain that result.

What you want is to:

.get("test").textValue();

which will return the actual content of the JSON String itself (with everything unescaped and so on).

Note that this will return null if the JsonNode is not a TextNode.

fge
  • 119,121
  • 33
  • 254
  • 329
  • 5
    And more generally, `JsonNode.toString()` should not be used for anything other than debugging or trouble-shooting: it is not (for example) appropriate for serialization. Instead. objectMapper.writeValueAsString(node) is the correct way, and handles all escaping/quoting aspects, using mapper configuration, possible indentation. – StaxMan Jun 16 '15 at 23:50
  • The correct method name is "getTextValue()". So this ...get("test").getTextValue() will give you the string value without quotes. – Hemant Nagpal Apr 18 '22 at 06:40
  • If the value you want to retrieve is not of type `String`, `textValue()` will return `null`. If the value type is `number`, you could use `intValue()` or `longValue()` to get the value you want. – Frank Wang Mar 22 '23 at 06:26
6

Simple generic ternary to use the non-quoted text, otherwise keep the node intact.

node.isTextual() ? node.asText() : node
Jon Polaski
  • 134
  • 2
  • 3
  • This worked. In the case that you want the node to be printed as a string with non-quoted text, the latter part of the ternary can be mapped to a string using `objectMapper.writeValueAsString(node)` – kjkurtz Jan 16 '18 at 15:23
  • The correct method name is "getTextValue()". So this `...get("test").getTextValue()` will give you the string value without quotes. – Hemant Nagpal Apr 18 '22 at 06:43
0

jsonValue.get("value").isString().stringValue()

Also check null before calling in single line methods

Thangaraj
  • 53
  • 1
  • 7