Dattatreya Kugve
Dattatreya Kugve

Reputation: 377

Jackson ObjectMapper is turning euro symbol into junk character

I have a object which has a field called currencySymbol which stores Euro symbol in one of its property of String type. When I convert this Object to json using Object mapper euro symbol is converted into a junk character. Below is the code I am using. Do I need to do any character encoding configuration before converting to JSON

public String convertObjectToJson(Object obj) {
    long start = System.currentTimeMillis();
    objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    String jsonBody = null;
    try {
        jsonBody = objectMapper.writeValueAsString(obj);
    } catch (JsonProcessingException e) {
        logger.info(e.getMessage(), e.fillInStackTrace());
    }
    logger.debug("Conversion time for object to json :: " + (System.currentTimeMillis() - start) / 1000d);
    return jsonBody;
}

Input object :

{"currencySymbol":"₹","currencyFormat":"₹0;-₹0"} 

JSON output:

{"currencySymbol":"Ç","currencyFormat":"Ç0;-Ç0"} 

As you can see post conversion 'Indian Rupee' symbol ₹ is turned to junk character. Same thing happens for Euro € symbol as well

Upvotes: 2

Views: 1893

Answers (2)

Ricky Sixx
Ricky Sixx

Reputation: 653

I'll post an answer because it may be useful to someone else.

I had a similar problem, but it turned out to not be Jackson's fault.

I was trying to serialize a string which contained the character to a JSON string using Jackson library (version 2.8.6).

I've tried to debug my code to see the value of the serialized JSON string and it contained the character, but in the console and in the log files I've always seen a junk character.

So it turned out to be a problem on the encoding used by my console and by my logging framework.

Just for reference, here is an answer on how to explicitly set the encoding used by a Logback appender. After setting this encoding, I was able to see the symbol in my log files.

Upvotes: 1

Dattatreya Kugve
Dattatreya Kugve

Reputation: 377

I am able to resolve this issue by setting config parameter JsonGenerator.Feature.ESCAPE_NON_ASCII to true. Below is the working code

public String convertObjectToJson(Object obj) {
    long start = System.currentTimeMillis();
    objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    objectMapper.getFactory().configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, true);
    String jsonBody = null;
    try {
        jsonBody = objectMapper.writeValueAsString(obj);
    } catch (JsonProcessingException e) {
        logger.info(e.getMessage(), e.fillInStackTrace());
    }
    logger.debug("Conversion time for object to json :: " + (System.currentTimeMillis() - start) / 1000d);
    return jsonBody;
}

Upvotes: 1

Related Questions