4
是否可以在JSON.NET中使用變音符號來編碼字符串,而序列化字符串是這樣編碼的?在JSON.NET中編碼變音符號
「平面」=> 「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();
}
}
第一次我忘了代碼... – sra 2011-05-10 17:20:17