2010-11-10 54 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:指定操作系统应创建一个新的文件。如果文件已经存在,它将被覆盖