问题
I am trying to save and load files from isolatedStorage based on this class by forum member Shawn Kendrot that i got throughout this forum post.
I’m able to save with no problem but when loading then deserialising the json file I am getting an error
“A first chance exception of type 'Newtonsoft.Json.JsonSerializationException'
occurred in Newtonsoft.Json.DLL”
I don’t know what I could be doing wrong, because the file is saved and it’s reading properly but not deserializing. The json file has 4 entries at the moment, but it will have 6 later on.
Can anyone help me understand what is wrong here?
It's this function:
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;
}
The problem is occurring on this line:
var data = JsonConvert.DeserializeObject<T>(json);
My 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");
}
}
}
回答1:
Your problem is - as you pointed out by yourself - you have no clue what to do with the return value.
FileStorage.ReadSharedData<MainPage>(FileName);
tries to parse your json string to an object of type MainPage which should have the properties Name
, ReleaseDate
and Genres
(which should be an IEnumerable).
Your MainPage
actually has no such properties, so your deserialization crashes.
Try the following:
public class Move
{
public string Name;
public string ReleaseDate;
public IEnumerable<string> Genres
}
And then call var deserializedMove = FileStorage.ReadSharedData<Movie>(FileName);
来源:https://stackoverflow.com/questions/21596564/deserializing-json-c-sharp-first-chance-exception-of-type-newtonsoft