ISO-8859-1 encoded strings out of /into JSON in Java

允我心安 提交于 2019-12-24 16:44:12

问题


My application has a Java servlet that reads a JSONObject out of the request and constructs some Java objects that are used elsewhere. I'm running into a problem because there are strings in the JSON that are encoded in ISO-8859-1. When I extract them into Java strings, the encoding appears to get interpreted as UTF-16. I need to be able to get the correctly encoded string back at some point to put into another JSON object.

I've tried mucking around with ByteBuffers and CharBuffers, but then I don't get any characters at all. I can't change the encoding, as I have to play nicely with other applications that use ISO-8859-1.

Any tips would be greatly appreciated.

It's a legacy application using Struts 1.3.8. I'm using net.sf.json 2.2.4 for JSONObject and JSONArray.

A snippet of the parsing code is:

final JSONObject a = (JSONObject) i;
final JSONObject attr = a.getJSONObject("attribute");
final String category = attr.getString("category");

final String value = attr.getString("value");

I then create POJOs using that information, that are retrieved by another action class to create JSON to pass to the client for display, or to pass to other applications.

So to clarify, if the JSON contains the string "Juan Guzmán", the Java String contains something like Juan Guzm?_An (I don't have the exact one in front of me). I'm not sure how to get the correct diacritical back. I believe that if I can get a Java String that contains the correct representation, that Mezzie's solution, below, will allow me to create the string with the correct encoding to put back into the JSON to serve back.


回答1:


I had the same issue and I am using the same technology as you are. In our case, it was UTF 8. so just change that to UTF-16

    public static String UTF8toISO( String str )
    {
        try
        {
            return new String( str.getBytes( "ISO-8859-1" ), "UTF-8" );
        }
        catch ( UnsupportedEncodingException e )
        {
            e.printStackTrace();
        }
        return str;
    }


来源:https://stackoverflow.com/questions/13593157/iso-8859-1-encoded-strings-out-of-into-json-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!