1

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");
    }
  }
}
Community
  • 1
  • 1
Bob Machine
  • 141
  • 4
  • 12
  • Could you save you data file out of `IsolatedStorageFile` then view it by Hex viewer? – Aimeast Feb 06 '14 at 07:57
  • View the file by hex viewer to watching what is the first char – Aimeast Feb 06 '14 at 08:14
  • use WinHex or XVI32 view the file. I just doubt the leading byte of the file. – Aimeast Feb 06 '14 at 08:29
  • Maybe there is the answer. Please try again after remove all non-ascii char – Aimeast Feb 06 '14 at 09:12
  • @Shawn Kendrot Maybe you could take a look at what I'm doing wrong and show me how to send, receive and then access the data. I tried ElGauchooo suggestion but it didn't work. I've been beating myself silly in the head last couple of days and cannot figure this out – Bob Machine Feb 06 '14 at 18:50

1 Answers1

0

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);

ElGauchooo
  • 4,256
  • 2
  • 13
  • 16
  • this is the json string `string json = @"{'Name': 'Bad Boys', 'ReleaseDate': '1995-4-7T00:00:00', 'Genres': [ 'Action', 'Comedy' ] }";` the method call is: `FileStorage.ReadSharedData>(FileName);` The next step was to use the retrieved data, but i didn't get that far – Bob Machine Feb 06 '14 at 08:07
  • Could you please provide the struct you're trying to deserialize this data to? – ElGauchooo Feb 06 '14 at 08:12
  • im not sure what u mean, I'm trying to retrieve it as key/value pairs. How would u suggest!? Bare with me I'm a noob in C# :) – Bob Machine Feb 06 '14 at 08:21
  • One of the things that has me a bit puzzled is those `T` & `` in the function signature, what does it mean? – Bob Machine Feb 06 '14 at 08:26
  • T means that you are using this method in a generic way. You can call `ReadSharedData(..)` and your code will try to deserialize your data into a `MyClassA` class. Call it with `ReadSharedData(..)` and it will deserialize it into a `MyOtherClass` object. Show us your *own* call. There you should see which type you're using - we need this class struct. – ElGauchooo Feb 06 '14 at 08:34
  • the call is being made from a backgroundAgent so it would be in that same class, is that what u mean? The other thing i wasn't sure about was what should the the return type on the function making the call. Maybe if u made a little example basing it on the FileStorage class on the link it would be easier for me to understand – Bob Machine Feb 06 '14 at 08:44
  • I assume you're having some code like `MySpecialClass.ReadSharedData(fileName);` If you have found this call, show me your `MyMovieClass` (properties and stuff...) – ElGauchooo Feb 06 '14 at 08:51
  • to simplify i did a new project and I'm calling it from MainPage like this `FileStorage.ReadSharedData(FileName);` It's suggesting we move to a chat, maybe it will be helpful, if you don't mind, ok? – Bob Machine Feb 06 '14 at 09:00
  • Oooops, didn't notice that. Nada bacana – Bob Machine Feb 06 '14 at 09:28
  • I have updated my post to include the MainPage, did u see it? – Bob Machine Feb 06 '14 at 10:07
  • well it's still giving me the `A first chance exception of type` and the other thing is then back on MainPage how do i access the retrieved values? – Bob Machine Feb 06 '14 at 11:13