2010-11-10 63 views
0

看來JSON.NET正在編寫無效的JSON,儘管如果這是由於我的濫用而引起的,我不會感到驚訝。JSON.NET寫入無效的JSON?

看來,它是重複JSON的最後幾個字符:

/* ... */ "Teaser":"\nfoo.\n","Title":"bar","ImageSrc":null,"Nid":44462,"Vid":17}]}4462,"Vid":17}]} 

的重複字符串是:

4462,"Vid":17}]} 

我打印出來到控制檯,所以我不認爲這是Visual Studio文本可視化工具中的一個錯誤。

序列化代碼:

 static IDictionary<int, ObservableCollection<Story>> _sectionStories; 
     private static void writeToFile() 
     { 
      IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication(); 
      using (IsolatedStorageFileStream stream = storage.OpenFile(STORIES_FILE, FileMode.OpenOrCreate)) 
      { 
       using (StreamWriter writer = new StreamWriter(stream)) 
       { 
        writer.Write(JsonConvert.SerializeObject(_sectionStories)); 
       } 

      } 

#if DEBUG 
      StreamReader reader = new StreamReader(storage.OpenFile(STORIES_FILE, FileMode.Open)); 
      string contents = reader.ReadToEnd(); 

      JObject data = JObject.Parse(contents); 
      string result = ""; 
      foreach (char c in contents.Skip(contents.Length - 20)) 
      { 
       result += c; 
      } 
      Debug.WriteLine(result); 

      // crashes here with ArgumentException 
      // perhaps because JSON is invalid? 
      var foo = JsonConvert.DeserializeObject<Dictionary<int, List<Story>>>(contents); 
#endif 
     } 

難道我做錯了什麼嗎?或者這是一個錯誤?有沒有已知的解決方法?

奇怪的是,JObject.Parse()不會引發任何錯誤。

我建立了Windows Phone的一個Silverlight應用程序7.

+0

目前還不清楚你指的是哪個重複以及底層結構是什麼。 – Aliostad 2010-11-10 18:16:10

+0

你確定這不是對象的一部分?如何有可能有一個重複的元素和文本是反序列化?我不相信。如果可以的話,放入整個JSON。 – Aliostad 2010-11-10 18:39:17

+0

X-Ref:http://stackoverflow.com/questions/4092985/datacontractserializer-problem-in-windows-phone-7 – 2010-11-11 09:26:46

回答

2

當寫入文件時指定

FileMode.OpenOrCreate 

如果該文件存在,並且比數據長16個字節,你打算寫它(從剛剛完成相同數據的舊數據版本開始),那麼當您完成新數據寫入時,數據仍然存在。

解決方案:

FileMode.Create 

來源: http://msdn.microsoft.com/en-us/library/system.io.filemode.aspx

FileMode.Create:指定操作系統應創建一個新的文件。如果文件已經存在,它將被覆蓋