簡體   English   中英

JSON.NET:無法翻譯Unicode字符

[英]JSON.NET: Unable to translate Unicode character

我實現了一個包含一些文本的搜索樹。 現在,我要允許客戶端將這棵樹保存到磁盤-序列化。 因此,我正在使用JSON.Net將此對象序列化到磁盤。 由於我要處理巨大的文本文件(50MB +),因此我將該對象直接序列化為DISK(而不是獲取包含此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()
    ...

未通過測試的文件是包含普通字符的文件(不確定這是問題所在)。

我該如何解決?

這不是JSON問題,而是StreamWriter問題,它遇到無法編碼的字符。 嘗試像這樣打開它:

using (StreamWriter sw = new StreamWriter(fs, Encoding.Unicode))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM