简体   繁体   English

C#-BinaryFormatter的人类可读序列化替代方案

[英]C# - Human readable serialization alternatives to BinaryFormatter

I have an object serialized via 我有一个通过序列化的对象

BinaryFormatter formatter = new BinaryFormatter();
StreamWriter writer = new StreamWriter("filename");
formatter.Serialize(writer.BaseStream, the_object);
writer.Close();

Is there a way to view it in a more understandable form, for example, in json? 有没有办法以更容易理解的形式查看它,例如在json中? Thanks 谢谢

Using Json.NET : 使用Json.NET

string serialized = JsonConvert.SerializeObject(the_object);

To deserialize it, you can either specify the object's type via generics: 要反序列化,可以通过泛型指定对象的类型:

YourEntity deserializedObject = JsonConvert.DeserializeObject<YourEntity>(serialized);

Or you can take advantage of dynamic (Requires C# 4.0 or newer): 或者,您可以利用动态功能 (需要C#4.0或更高版本):

dynamic deserializedObject = JsonConvert.DeserializeObject(serialized);

I believe that the only way to "view" a serialized object in a particular format is to serialize it into that form first. 我认为,以特定格式“查看”序列化对象的唯一方法是首先将其序列化为该形式。 You are not going to be able to take a binary-serialized object and look at it in JSON, unless you want to write a ton of code to transform a binary object to JSON. 除非要编写大量代码将二进制对象转换为JSON,否则您将不能使用二进制序列化的对象并以JSON对其进行查看。 But that would be a complete waste of time. 但这将完全浪费时间。

If the data is already serialized in binary, then deserialize it into class objects and then re-serialize it into JSON or XML. 如果数据已经以二进制序列化,则将其反序列化为类对象,然后将其重新序列化为JSON或XML。 Then you can open those files and understand what the contents are. 然后,您可以打开这些文件并了解内容。

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

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