Gson Unicode characters conversion to Unicode character codes

前端 未结 2 663
眼角桃花
眼角桃花 2020-12-22 00:17

Check out my code below. I have a JSON string which contains Unicode character codes. I convert it to my Java object and then convert it back to JSON string. However, you ca

2条回答
  •  自闭症患者
    2020-12-22 01:12

    There is a question that is marked as duplicate of this one: unicode characters in json file to be unconverted after managing java gson [duplicate] . I answered that question and the answer was accepted as appropriate solution. So below is a copy of my answer:

    Actually, big advantage of unicode characters is that any client reads and treats the code "\u..." just the same as its character representation. For instance if in html file if you replace every single character with its unicode representation the browser will read it as usual. I.e. replace 'H' in "Hello world" with '\u0048' (which is unicode for 'H') and in the browser you will still see "Hello world". But in this case it works against you as Gson simply replaces unicodes with their symbols.

    My suggestion may not be perfect but it will work. Before converting your Object remember the location of your unicode symbols and after conversion change them back to unicodes. Here is the tool that may help you: There is an open source library MgntUtils (written by me) that has a utility that converts any string to sequence of unicodes and vise-versa.

    You can do:

    String s = StringUnicodeEncoderDecoder.encodeStringToUnicodeSequence("Hello world");
    

    And it will give you String: "\u0048\u0065\u006c\u006c\u006f\u0020\u0077\u006f\u0072\u006c\u0064" and then you can do this:

        String s 
    = StringUnicodeEncoderDecoder.decodeUnicodeSequenceToString("\u0048\u0065\u006c\u006c\u006f\u0020\u0077\u006f\u0072\u006c\u0064");
    

    And it will return you String "Hello world". It works with any language. Here is the link to the article that explains where to get the library: Open Source Java library with stack trace filtering, Silent String parsing Unicode converter and Version comparison. Look for paragraph titled "String Unicode converter"

    Here is the link to Maven artifacts and here is a link to Github with sources and javadoc included.Here is javadoc

提交回复
热议问题