Serialize an object using DataContractJsonSerializer

user1499352 picture user1499352 · Jul 8, 2012 · Viewed 7.3k times · Source

I have created a generic extension method to serialize JSON using the DataContractJsonSerializer. looks like this:

public static string ToJSON<T>(this T obj) where T : class
{
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
    using (MemoryStream stream = new MemoryStream())
    {
       serializer.WriteObject(stream, obj);
       return Encoding.Default.GetString(stream.ToArray());
    }
}

I need to create a class, when serialize to json it should be like this :

{
     "expiration": "2011-04-20T11:54:21.032Z",
     "conditions": [
        ["eq", "acl", "private"],
        ["eq", "bucket": "myas3bucket"],
        ["eq", "$key", "myfilename.jpg"],
        ["content-length-range", 0, 20971520],
        ["eq", "$redirect", "myredirecturl"],
     ]
}

What are the attributes of this class?

Thanks,

Answer

greg84 picture greg84 · Jul 8, 2012

This should do the job:

DateTime expiration { get; set; }
string[][] conditions { get; set; }

You could also make conditions a List<List<string>>, or anything that's IEnumerable<IEnumerable<string>>, even List<string[]> should work.