简体   繁体   English

C#以易于阅读的文本将对象写入文件

[英]C# write object to file in human-readable text

Do there exist any standard mechanisms or processes to output any C# object to file in human-readable text format ? 是否存在任何标准机制或过程来以人类可读的文本格式将任何C#对象输出到文件?

Unlike serialization ( BinaryFormatter.Serializer ) this would not ever require reading back the object from file. 与序列化( BinaryFormatter.Serializer )不同,这永远不需要从文件中读取对象。

There are many different "human readable" formats you could use to represent data (XML, JSON, YAML, etc). 有许多不同的“人类可读”的格式,你可以用它来表示数据(XML,JSON,YAML等)。 A common one is JSON. 常见的是JSON。

There is a library called JSON.NET that is very heavily used in the .NET community for handling JSON. 有一个名为JSON.NET的库,在.NET社区中非常常用,用于处理JSON。 You can use built in .NET methods but I prefer this nuget package. 您可以使用内置的.NET方法,但我更喜欢此nuget包。 With JSON.NET you can do something as simple as: 使用JSON.NET,您可以执行以下操作:

MyClass someObject = new MyClass();
someObject.SomeProperty = "Foo";
someObject.SomeOtherProperty = "Bar";
string json = JsonConvert.SerializeObject(someObject);

That string "json" would look similar to this: 该字符串“ json”将类似于以下内容:

{
    "SomeProperty":"Foo",
    "SomeOtherProperty":"Bar"
}

I made a fiddle here that shows a sample class I created and how it looks when its serialized into JSON. 我在这里做了一个小提琴,显示了我创建的示例类以及将其序列化为JSON时的外观。

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

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