Search code examples
c#-4.0json.netdatacontractdatacontractjsonserializer

Serialize an object with DataContractJsonSerializer


I have a class which contains some items. I want to serialize an instance of this class to json using the DataContractJsonSerializer :

[DataContract]
public class Policy
{
    private string expiration { get; set; }
    private List<List<string>> conditions { get; set; }
    public Policy(){}
    public Policy(string expiration, List<List<string>> conditions){
        this.expiration = expiration;
        this.conditions = conditions;
    }
    [DataMember]
    public string DateExpiration
    {
        get{ return expiration;}
        set{expiration = value;}
    }
    [DataMember]
    public List<List<string>> Conditions
    {
        get{return conditions;}
        set{conditions = value;}
    }
}

When serialized 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"],
  ]
}

I tried like this but nothing :

        string expiration = "2012-12-01T12:00:00.000Z";            
        List<List<string>> conditions = new List<List<string>>()
        {
            new List<string>(){ "[ eq", "acl", "private ]" }, 
            new List<string>(){ "[ eq", "bucket", "myas3bucket]" },
            new List<string>(){ "[ eq", "$key", "myfilename.jpg ]" },
            new List<string>(){ "[ content-length-range", "0", "20971520]" },
            new List<string>(){ "[ eq", "$redirect", "myredirecturl]" }
        };

        Policy myPolicy = new Policy(expiration,conditions);
        string policy = JSONHelper.Serialize<Policy>(myPolicy);

thanks


Solution

  • First off... your class needs a little help:

    [DataContract] 
    public class Policy 
    { 
        public Policy(){} 
        public Policy(string expiration, List<List<string>> conditions){ 
            this.DateExpiration = expiration; 
            this.Conditions = conditions; 
        } 
        [DataMember] 
        public string DateExpiration { get; set; } 
    
        [DataMember] 
        public List<List<string>> Conditions { get; set; }
    
    }
    

    Try removing the brackets in your lists:

        string expiration = "2012-12-01T12:00:00.000Z";             
        List<List<string>> conditions = new List<List<string>>() 
        { 
            new List<string>(){ "eq", "acl", "private" },  
            new List<string>(){ "eq", "bucket", "myas3bucket" }, 
            new List<string>(){ "eq", "$key", "myfilename.jpg" }, 
            new List<string>(){ "content-length-range", "0", "20971520" }, 
            new List<string>(){ "eq", "$redirect", "myredirecturl" } 
        }; 
    
        Policy myPolicy = new Policy(expiration,conditions); 
        string policy = JSONHelper.Serialize<Policy>(myPolicy);