2012-07-08 91 views
-2

我有一個包含一些項目的類。我想序列化這個類的一個實例,使用DataContractJsonSerializer到JSON:使用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;} 
    } 
} 

當序列化JSON它應該是這樣的:

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

我想這樣的,但沒有:

 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); 

謝謝

+0

請界定 「無」。錯誤?空值?什麼? – 2012-07-08 18:53:36

+0

@Chris Gessler nothing:dosn't給格式json我提到 – user1499352 2012-07-08 18:56:52

回答

0

首先,你的班級需要一點幫助:

[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; } 

} 

嘗試在你的列表中去掉括號:

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); 
+0

謝謝格斯勒, – user1499352 2012-07-08 19:10:23

相關問題