我想保存和加載文件從isolatedStorage基於this class由論壇成員Shawn Kendrot,我得到了整個this forum post。反序列化JSON C#「第一次機會異常的類型 - newtonsoft」
我能夠保存沒有問題,但裝載然後deserialising JSON文件時,我得到一個錯誤
「A first chance exception of type 'Newtonsoft.Json.JsonSerializationException'
occurred in Newtonsoft.Json.DLL」
我不知道我可以做錯誤的,因爲該文件被保存它正在正確讀取,但不是反序列化。 json文件目前有4個條目,但是稍後會有6個條目。
任何人都可以幫我理解這裏有什麼問題嗎?
它的這個功能:
public static T ReadSharedData<T>(string fileName) where T : class, new()
{
T result = new T();
var mutex = GetMutex(fileName);
mutex.WaitOne();
fileName = GetSharedFileName(fileName);
try
{
var storage = IsolatedStorageFile.GetUserStoreForApplication();
if (storage.FileExists(fileName))
{
using (var fileStream = storage.OpenFile(fileName, FileMode.Open, FileAccess.Read))
{
using (var reader = new StreamReader(fileStream))
{
string json = reader.ReadToEnd();
if (string.IsNullOrEmpty(json) == false)
{
var data = JsonConvert.DeserializeObject<T>(json);
if (data != null)
{
result = data;
}
}
}
}
}
}
catch { }
finally
{
mutex.Release();
}
return result;
}
的問題是在這條線出現:
var data = JsonConvert.DeserializeObject<T>(json);
我MainPage.xaml.cs中
using Microsoft.Phone.Shell;
using JSON_Storage_Test.Resources;
using System.Diagnostics;
using System.Text;
using System.IO.IsolatedStorage;
namespace JSON_Storage_Test
{
public partial class MainPage : PhoneApplicationPage
{
private const string FileName = 「movieSettings.json";
// Constructor
public MainPage()
{
InitializeComponent();
}
private void SaveJ_Click(object sender, RoutedEventArgs e)
{
string json = @"{
'Name': 'Bad Boys',
'ReleaseDate': '1995-4-7T00:00:00',
'Genres': [ 'Action', 'Comedy' ]
}";
FileStorage.WriteSharedData("movieSettings.json", json);
}
//Im not sure here, what should the return type be
//and how would i then access the retrieved data
private void LoadJ_Click(object sender, RoutedEventArgs e)
{
FileStorage.ReadSharedData<MainPage>(FileName);
Debug.WriteLine("Load clicked");
}
}
}
你能救你的數據文件出來'IsolatedStorageFile'然後用十六進制查看器來查看呢? – Aimeast
通過十六進制查看器查看文件第一個字符是什麼 – Aimeast
使用WinHex或XVI32查看文件。我只是懷疑文件的前導字節。 – Aimeast