【发布时间】:2015-01-13 00:41:18
【问题描述】:
我实现了一个包含一些文本的搜索树。现在,我想让客户端将此树保存到磁盘 - 序列化。因此,我使用 JSON.Net 将此对象序列化到磁盘。由于我正在处理巨大的文本文件(50MB+),我将这个对象直接序列化到磁盘(而不是获取包含这个 JSON 的字符串)。
这是我当前的代码:
public void Save(string path)
{
using (FileStream fs = File.Open(path, FileMode.OpenOrCreate))
using (StreamWriter sw = new StreamWriter(fs))
using (JsonWriter jw = new JsonTextWriter(sw))
{
jw.Formatting = Formatting.Indented;
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(jw, this);
}
}
这是我遇到的例外情况:
exception:
System.Text.EncoderFallbackException: Unable to translate Unicode character \uD859 at index 485 to specified code page.
Result StackTrace:
at System.Text.EncoderExceptionFallbackBuffer.Fallback(Char charUnknown, Int32 index)
at System.Text.EncoderFallbackBuffer.InternalFallback(Char ch, Char*& chars)
at System.Text.UTF8Encoding.GetBytes(Char* chars, Int32 charCount, Byte* bytes, Int32 byteCount, EncoderNLS baseEncoder)
at System.Text.EncoderNLS.GetBytes(Char* chars, Int32 charCount, Byte* bytes, Int32 byteCount, Boolean flush)
at System.Text.EncoderNLS.GetBytes(Char[] chars, Int32 charIndex, Int32 charCount, Byte[] bytes, Int32 byteIndex, Boolean flush)
at System.IO.StreamWriter.Flush(Boolean flushStream, Boolean flushEncoder)
at System.IO.StreamWriter.Dispose(Boolean disposing)
at System.IO.TextWriter.Dispose()
...
未通过测试的文件是包含 chanise 字符的文件(不确定这是问题所在)。
我该如何解决这个问题?
【问题讨论】:
-
好吧,U+D859 本身并不是一个有效的 Unicode 字符——它是代理对的一部分。我的猜测是您的某些数据无效...您应该找出问题所在。
标签: c# json text unicode json.net