简体   繁体   中英

Escape Latin-1 ( ISO-8859-1) to utf-8 String in Java

I tried to use Gson and org.json as the examples. I tried Commons Text as well, but I doesn't work for me, when I import the library manually (I not allowed to use Maven). So I decided to search for another solution.

NoClassDefFoundError: org/apache/commons/text/StringEscapeUtils

I need to escape an Array to Json this way. Especially Ó , ó or any Latin-1 character( Not escape " , just escape what is in "&%$/"Helló" ). Original message: Helló / // \\ "WÓRLD"

{"token":"045-245","message":"Helló / // \\ \"WÓRLD\" "}

to

{"token":"045-245","message":"Hell\u00F3 / // \\ \"W\u00D3RLD\" "}

This what I get when I use:

Gson

JsonObject json = new JsonObject();
json.addProperty("token", "045-245");
json.addProperty("message", "Helló WÓRLD");
String payload = new Gson().toJson(json);
System.out.println(payload);

Result:

{"token":"045-245","message":"Helló WÓRLD"}

org.json

JSONObject jsonObject = new JSONObject();        
jsonObject.put("token", "045-245");
jsonObject.put("message", "Helló WÓRLD");
System.out.println(jsonObject.toString());

Result:

{"message":"Helló WÓRLD","token":"045-245"}

Thanks to @dnault I found Jackson Json Library. I needed to import com.fasterxml.jackson.core , com.fasterxml.jackson.databind . I imported com.fasterxml.jackson.annotations as well, for no problems on JDK 8.

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

public class Foo {

    ObjectMapper mapper = new ObjectMapper();
    mapper.getFactory().configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, true);
    ObjectNode node = mapper.getNodeFactory().objectNode();
    node.put("token", "045-245");
    node.put("message", "Helló / // \\ \"WÓRLD\" ");
    System.out.println(mapper.writeValueAsString(node));

}

Output:

{"token":"045-245","message":"Hell\u00F3 / // \\ \"W\u00D3RLD\" "}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM