Anil Gara
Anil Gara

Reputation: 21

Jackson Json Escaping

I created json using Jackson. It is working fine. But while parsing json using jackson i had issues in Escaping trademark symbol. can any one please suggest me how to do escape in json jackson provided library. Thanks in advance.

Upvotes: 1

Views: 7218

Answers (1)

wassgren
wassgren

Reputation: 19201

Well, basically you don't have to do that. I have written a small test case to show you what I mean:

public class JsonTest {
    public static class Pojo {
        private final String value;

        @JsonCreator
        public Pojo(@JsonProperty("value") final String value) {
            this.value = value;
        }

        public String getValue() {
            return value;
        }
    }

    @Test
    public void testRoundtrip() throws IOException {
        final ObjectMapper objectMapper = new ObjectMapper();
        final String value = "foo ™ bar";
        final String serialized = objectMapper.writeValueAsString(new Pojo(value));
        final Pojo deserialized = objectMapper.readValue(serialized, Pojo.class);
        Assert.assertEquals(value, deserialized.getValue());
    }
}

The above illustrates that the trademark symbol can be serialized and deserialized without escaping.


With that being said, to solve your problem make sure that you are reading the input using the correct encoding. The encoding can e.g. be set when opening the URL or opening the file

BufferedReader urlReader = new BufferedReader(
        new InputStreamReader(
                url.openStream(), "UTF-8"));

BufferedReader in = new BufferedReader(
        new InputStreamReader(
                new FileInputStream(file), "UTF-8"));

Also, if you wish to escape characters you do that by using the \ character.

From the docs on json.org:

A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string. A string is very much like a C or Java string.

Upvotes: 2

Related Questions