C#二进制序列化错误
C# binary serialization error
就是这样,
我有以下 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();
我收到一条错误消息:
Type 'Newtonsoft.Json.Linq.JObject' in Assembly 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=xxxxxxxxxxxxxxx' is not marked as serializable.
我不知道如何继续。有什么我想念的吗?有任何想法吗?谢谢!
要使用 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
,然后序列化该实例。
就是这样,
我有以下 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();
我收到一条错误消息:
Type 'Newtonsoft.Json.Linq.JObject' in Assembly 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=xxxxxxxxxxxxxxx' is not marked as serializable.
我不知道如何继续。有什么我想念的吗?有任何想法吗?谢谢!
要使用 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
,然后序列化该实例。