What is the difference between asText() and toString() in JsonNode?

So I’m trying to validate some payload after POSTing.

The payload (JSON) looks like the follow:

{"value":""<html><body><a href='http://www.example.com'>Hi there!</a></body></html>""}

Then I tried to convert the above to JsonNode and extract the “value“‘s value. However, the two methods, asText() & toString(), return different string values.

How do these two methods work differently?

Given the String ""<html><body><a href='http://www.example.com'>Hi there!</a></body></html>""

toString returns "<html><body><a href='http://www.example.com'>Hi there!</a></body></html>"

asText() returns <html><body><a href='http://www.example.com'>Hi there!</a></body></html>

Answer

asText ()

It is an abstract method from JsonNode, which is overriden in TextNode. And, as per its implementation, it supposed to return the value without any manipulation.

@Override
public String asText() {
    return _value;
}

toString ()

It is overridden from Object. So, it is textual representation of an object. So, toString actually returns you the complete textual form on your given object. And, per its implementation in TextNode. It appends quoting (at the beginning and end) to your value.

/**
 * Different from other values, Strings need quoting
 */
@Override
public String toString()
{
    int len = _value.length();
    len = len + 2 + (len >> 4);
    return new StringBuilder(len)
            // 09-Dec-2017, tatu: Use apostrophes on purpose to prevent use as JSON producer:
            .append(''')
            .append(_value)
            .append(''')
            .toString();
}

And, you can also see the same difference when you print them.

Leave a Reply

Your email address will not be published. Required fields are marked *