简体   繁体   English

C#二进制序列化错误

[英]C# binary serialization error

So here it goes, 所以就这样,

I have the following JSON string: 我有以下JSON字符串:

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

And I have de-serialize it using Newtonsoft.JSON as the following: 我已经使用Newtonsoft.JSON将其反序列化如下:

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. 问题是,我有一项要求,要求我使用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. 程序集“ Newtonsoft.Json,版本= 6.0.0.0,区域性=中性,PublicKeyToken = xxxxxxxxxxxxxxx”中的类型“ Newtonsoft.Json.Linq.JObject”未标记为可序列化。

I have no idea how to continue. 我不知道如何继续。 Is there something i'm missing? 有什么我想念的吗? Any ideas? 有任何想法吗? Thanks! 谢谢!

To use BinaryFormatter , you'll need to create serializable classes to match the data in your JSON. 要使用BinaryFormatter ,您需要创建可序列化的类以匹配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. 然后,您可以从JSON反序列化为Foo ,然后序列化该实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM