用 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();
        }

    }

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

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
    }
}

相关内容

  • 没有找到相关文章

最新更新