在JSON.NET中编码变音符号

时间:2011-05-10 17:09:00

标签: .net json.net

是否可以在JSON.NET中使用变音符号对字符串进行编码,以便序列化字符串像这样编码?

“Pläne”=> “PL \ u00e4ne”

更新 在sra anwser之后,我想出了以下适用于我的代码。

public class Utf8Converter : JsonConverter
    {
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            string s = (string)value;
            s = EncodeNonAsciiCharacters(s);            
            writer.WriteValue(s);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
                                        JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }

        public override bool CanConvert(Type objectType)
        {
            return typeof(string).IsAssignableFrom(objectType);
        }


        private static string EncodeNonAsciiCharacters(string value)
        {
            StringBuilder sb = new StringBuilder();
            foreach (char c in value)
            {
                if (c == '\t')
                    sb.Append(@"\t");
                else if (c == '\n')
                    sb.Append(@"\n");
                else if (c == '\r')
                    sb.Append(@"\r");
                else if (c > 127)
                {

                    string encodedValue = @"\u" + ((int)c).ToString("x4");
                    sb.Append(encodedValue);
                }
                else
                {
                    sb.Append(c);
                }
            }
            return sb.ToString();
        }



    }

1 个答案:

答案 0 :(得分:4)

是的,您可以使用自定义转换器为您执行此操作

internal class CustomConverter : JsonConverter
{
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        // your code
    }

    public override bool CanConvert(Type objectType)
    {
        // your code
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        // your code
    }
}