views:

837

answers:

3

Is there a way in .NET 2.0 (C#) to serialize object like you do using XmlSerializer in a simple / customizable human readable format thats for instance looks like PXLS or JSON? Also I know that XML is human readable, I'm looking for something with less annoying redundancy, something that you can output to the console as a result for the user.

+1  A: 

The built-in serialization options for .Net are Xml, Xml-Soap, and binary. Since you've ruled out xml and binary is definitely not human readable, you'll have to roll your own.

When rolling your own, you have a few options:

  • Add Utility or Extention methods to the class, like AviewAnew suggested
  • Extend System.Runtime.Serialization.Formatter / Implement System.Runtime.Serialization.IFormatter
  • Find a generic component online via google that will do what you want.

Note that the 2nd item can be specialized for your specific class (it doesn't have to be able to handle any class, if you don't want it to) and the latter two items are not mutually exclusive.

I have searched for a .Net JSON formatter in the past, and there are definitely multiple options out there. However, I ended up going a different direction that time. I just didn't feel very confident in any of them. Maybe someone else can provide a more specific recommendation. JSON is becoming big enough that hopefully Microsoft will include "native" support for it in the framework soon.

Joel Coehoorn
I could write my own HumanSerializer that is reflecting the type of object that were given to it - but this would consume way too much time. I thought that there already could be someone who solved this problem before - but google didn't find him or her.
Martin
+3  A: 

To Serialize into JSON in .NET you do as follows:

public static string ToJson(IEnumerable collection)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(collection.GetType());
            string json;
            using (MemoryStream m = new MemoryStream())
            {
                XmlDictionaryWriter writer = JsonReaderWriterFactory.CreateJsonWriter(m);
                ser.WriteObject(m, collection);
                writer.Flush();

                json = Encoding.Default.GetString(m.ToArray());
            }
            return json;
        }

The collections item need to have the "DataContract" attribute, and each member you wish to be serialized into the JSON must have the "DataMember" attibute.

It's possible that this only works for .NET 3.5. But there is an equally simple version for 2.0 aswell...

ullmark
Some minutes ago by using [Json.NET](http://www.codeplex.com/Json) I found out that JSON is not the best way to do it since it did not support Enums. The result is a number that is not very human readable aswell.
Martin
Okej, well the implementation all depends on what you are serializing.. If it's only one type with few members why not just override "ToString" and return a string.Format in whatever format you'd like
ullmark
A: 

I found a exaustive documentation here:

http://pietschsoft.com/post/2008/02/NET-35-JSON-Serialization-using-the-DataContractJsonSerializer.aspx

with this usefull class (support generics)

using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;

public class JSONHelper
{
  public static string Serialize<T>(T obj)
  {
      DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
      MemoryStream ms = new MemoryStream();
      serializer.WriteObject(ms, obj);
      string retVal = Encoding.Default.GetString(ms.ToArray());
      ms.Dispose();
      return retVal;
  }

  public static T Deserialize<T>(string json)
  {
      T obj = Activator.CreateInstance<T>();
      MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
      DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
      obj = (T)serializer.ReadObject(ms);
      ms.Close();
      ms.Dispose();
      return obj;
  }
}
Zax