【问题标题】:C# binary serialization errorC#二进制序列化错误
【发布时间】:2015-09-17 13:21:14
【问题描述】:

就这样吧,

我有以下 JSON 字符串:

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

我已经使用 Newtonsoft.JSON 对其进行反序列化,如下所示:

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

问题是,我有一个要求,要求我使用 BinaryFormatter 将该对象序列化为二进制文件。并通过执行以下操作:

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

我收到一条错误消息:

程序集“Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=xxxxxxxxxxxxxxx”中的类型“Newtonsoft.Json.Linq.JObject”未标记为可序列化。

我不知道如何继续。有什么我想念的吗?有任何想法吗?谢谢!

【问题讨论】:

    标签: c# json json.net serializable binaryformatter


    【解决方案1】:

    要使用BinaryFormatter,您需要创建可序列化的类来匹配 JSON 中的数据。比如:

    // 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; }
    }
    

    然后您可以从 JSON 反序列化为 Foo,然后序列化该实例。

    【讨论】:

    • 这是否意味着我无法将动态对象序列化为二进制文件?是否有其他解决方法可以让我这样做?无论如何,非常感谢,伙计!
    • @GalihDonoPrabowo:其实并不存在“动态对象”这样的东西——你正试图序列化一个JObjectBinaryFormatter 不知道您的变量使用了dynamic。就我个人而言,我建议尝试摆脱这种要求 - .NET 二进制格式化程序非常脆弱并且在各种方面都很烦人......如果您的真正要求是紧凑的表示,还有很多其他选择。 (而且“二进制文件”并不一定意味着“使用 .NET 二进制序列化”……)
    • [Serializable] 标记类可能比实现ISerializable 更简单。
    • 需求下降!谢谢一群人! [^_^]
    猜你喜欢
    • 1970-01-01
    • 2016-07-27
    • 2017-10-18
    • 1970-01-01
    • 2010-12-17
    • 2016-02-21
    • 1970-01-01
    • 1970-01-01
    • 2011-06-08
    相关资源
    最近更新 更多