[英]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();
我收到一個錯誤消息:
程序集“ Newtonsoft.Json,版本= 6.0.0.0,區域性=中性,PublicKeyToken = xxxxxxxxxxxxxxx”中的類型“ Newtonsoft.Json.Linq.JObject”未標記為可序列化。
我不知道如何繼續。 有什么我想念的嗎? 有任何想法嗎? 謝謝!
要使用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
,然后序列化該實例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.