1

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!

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

does that mean that i can't serialize dynamic object into binary file? is there another work around that allows me to do so? Anyways, many thanks, mate!
@GalihDonoPrabowo: Well there's no such thing as a "dynamic object" really - you're trying to serialize a JObject. The BinaryFormatter has no idea that your variable uses dynamic. Personally I'd recommend trying to get rid of the requirement - the .NET binary formatter is pretty fragile and annoying in various ways... if your real requirement is a compact representation, there are lots of other options. (And "binary file" doesn't imply "using .NET binary serializatoin" necessarily...)
Likely marking the class with [Serializable] would be simpler than implementing ISerializable.
Requirement dropped! Thanks a bunch guys! [^_^]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.