Mubbasher Khaliq
Mubbasher Khaliq

Reputation: 379

Convert UTF-16 unicode characters to UTF-8 in java

When I got JSON then there are \u003c and \u003e instead of < and >. I want to convert them back to utf-8 in java. any help will be highly appreciated. Thanks.

Upvotes: 23

Views: 68099

Answers (3)

shubham gulati
shubham gulati

Reputation: 1

You can also try this

String s = "Hello World!";
String convertedInUTF8 = new String(s, StandardCharsets.US_ASCII);

Upvotes: 0

Rocky
Rocky

Reputation: 951

You can try converting the string into a byte array

byte[] utfString = str.getBytes("UTF-8") ;

and convert that back to a string object by specifying the UTF-8 encoding like

str = new String(utfString,"UTF-8") ;

Upvotes: 2

Hemant Metalia
Hemant Metalia

Reputation: 30648

try {
    // Convert from Unicode to UTF-8
    String string = "\u003c";
    byte[] utf8 = string.getBytes("UTF-8");

    // Convert from UTF-8 to Unicode
    string = new String(utf8, "UTF-8");
} catch (UnsupportedEncodingException e) {
}

refer http://www.exampledepot.com/egs/java.lang/unicodetoutf8.html

Upvotes: 14

Related Questions