user2934977
user2934977

Reputation: 1

Encode Json Object Data with UTF-8 in java

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.*/

Upvotes: 0

Views: 5196

Answers (1)

Raymond Reddington
Raymond Reddington

Reputation: 1837

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); 

Upvotes: 1

Related Questions