jaghan varma
jaghan varma

Reputation: 19

Java UTF-8 not working properly for JSON

I am using spring rest template for getting rest API.

When I try to print the output, I get unwanted Characters.

Here is my code:

RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> apiResponse = restTemplate.getForEntity(url,String.class);
        return apiResponse.getBody();

Output is:

{"status":"FAILURE","error_code":"ITI","message":"Invalid Transaction Id","time":"30-03-2017 11:47:32"}

After getting this error I added UTF-8 Charecter encoding in the rest client:

public static String exicute(String url) {          
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("utf-8")));
        ResponseEntity<String> apiResponse = restTemplate.getForEntity(url,String.class);
        return apiResponse.getBody();           
    }

After that OUTPUT GOT changed but now ? in front of the result.

?{"status":"FAILURE","error_code":"ITI","message":"Invalid Transaction Id","time":"30-03-2017 11:49:34"}

How can i solve this issue?

Upvotes: 0

Views: 1294

Answers (1)

MC Emperor
MC Emperor

Reputation: 23057

 in front of the message is because the input stream has a byte order mark (BOM) at the beginning of the stream. The byte order mark is a Unicode character often at the beginning of the byte sequence which signals that the following bytes are encoded in UTF-8.

The character itself is often encoded as UTF-8 as well. It is then encoded as 0xEF,0xBB,0xBF, and it is often displayed as .

its only use in UTF-8 is to signal at the start that the text stream is encoded in UTF-8

That character is actually not part of the contents itself; instead it is merely a piece of metadata.

How to fix it?
The creator of the byte sequence (often a file, but it can also be some byte stream over the network) should remove it, in my opinion.

But on the other hand, you can easily remove it by replacing the character by an empty string.

string.replace("\uFEFF", "");

code piece copied from this post

Upvotes: 2

Related Questions