0

Suppose any special characters in my JSON data, they need to be encoded with UTF-8.

Example JSON:

String msg = { \"name\": \"SÅi®äjesh\", \"location\":\"Öslö" };

I tried below Scenarios

byte[] utf8Bytes = msg.getBytes(StandardCharsets.UTF_8);
String newString = new String(utf8Bytes, StandardCharsets.UTF_8);

/* Showing ? mark symbols in my Console */

System.out.println(URLEncoder.encode( original,StandardCharsets.UTF_8.toString() ));

/* Encodes the total String including {, " etc symbols.*/

asked Dec 3, 2019 at 6:56
2
  • It's better to share a sample of code that you wrote. That way, people can give feedback on how it can be improved. Commented Dec 3, 2019 at 7:04
  • I tried with below scenarios. But, it encodes the whole JSON string including all characters String json = "{ \"name\": \"SÅi®äjesh\", \"location\":\"Öslö\" }"; System.out.println(URLEncoder.encode( json,StandardCharsets.UTF_8.toString() )); Commented Dec 3, 2019 at 7:25

1 Answer 1

1

Java string are UTF-16, you need to convert it to a byte array then to utf8 string.

import static java.nio.charset.StandardCharsets.*;
byte[] bytes = "YOUR JSON".getBytes(ISO_8859_1); 
String jsonStr = new String(bytes, UTF_8); 
answered Dec 3, 2019 at 7:08
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Zaven. I tried this code. But, it shows output as ? symbols in my console

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.