C# write object to file in human-readable text

1.2k Views Asked by At

Do there exist any standard mechanisms or processes to output any C# object to file in human-readable text format ?

Unlike serialization ( BinaryFormatter.Serializer ) this would not ever require reading back the object from file.

1

There are 1 best solutions below

0
maccettura On

There are many different "human readable" formats you could use to represent data (XML, JSON, YAML, etc). A common one is JSON.

There is a library called JSON.NET that is very heavily used in the .NET community for handling JSON. You can use built in .NET methods but I prefer this nuget package. With JSON.NET you can do something as simple as:

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

That string "json" would look similar to this:

{
    "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.