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.*/
-
It's better to share a sample of code that you wrote. That way, people can give feedback on how it can be improved.Ankit Kante– Ankit Kante2019年12月03日 07:04:00 +00:00Commented 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() ));user2934977– user29349772019年12月03日 07:25:00 +00:00Commented Dec 3, 2019 at 7:25
1 Answer 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
Raymond Reddington
1,8471 gold badge15 silver badges21 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
user2934977
Thanks Zaven. I tried this code. But, it shows output as ? symbols in my console
default