Search code examples
c#jsonjson.netserializablebinaryformatter

C# binary serialization error


So here it goes,

I have the following JSON string:

{"sTest":"Hello","oTest":{"vTest":{},iTest:0.0}}

And I have de-serialize it using Newtonsoft.JSON as the following:

Dictionary<string, dynamic> obj = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(json)

The problem is, I have a requirement that requires me to serialize that object into a binary file using BinaryFormatter. And by doing the following:

Stream stream = new FileStream(System.Web.HttpContext.Current.Server.MapPath("~/_etc/") + "obj.dat", FileMode.Create, FileAccess.ReadWrite, FileShare.Read);
BinaryFormatter serializer = new BinaryFormatter();
serializer.Serialize(stream, e.props);
stream.Close();

I got an error saying:

Type 'Newtonsoft.Json.Linq.JObject' in Assembly 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=xxxxxxxxxxxxxxx' is not marked as serializable.

I have no idea how to continue. Is there something i'm missing? Any ideas? Thanks!


Solution

  • To use BinaryFormatter, you'll need to create serializable classes to match the data in your JSON. So for example:

    // I'm hoping the real names are rather more useful - or you could use
    // Json.NET attributes to perform mapping.
    [Serializable]
    public class Foo
    {
        public string sTest { get; set; }
        public Bar oTest { get; set; }
    }
    
    [Serializable]
    public class Bar
    {
        public List<string> vTest { get; set; }
        public double iTest { get; set; }
    }
    

    Then you can deserialize from JSON to a Foo, and then serialize that instance.