2014-03-29 107 views
0

我拉我的頭髮試圖序列一份政策文件,所以我可以開始使用Amazon Web Services的S3存儲。AWS S3序列化政策文件

http://aws.amazon.com/articles/1434介紹了政策文件的格式如下:

{"expiration": "2009-01-01T00:00:00Z", 
    "conditions": [ 
    {"bucket": "s3-bucket"}, 
    ["starts-with", "$key", "uploads/"], 
    {"acl": "private"}, 
    {"success_action_redirect": "http://localhost/"}, 
    ["starts-with", "$Content-Type", ""], 
    ["content-length-range", 0, 1048576] 
    ] 
} 

我如何序列化這在C#?我試着創建一個通用類是這樣的:

[DataContract] 
public class S3PolicyDocument 
{ 
    [DataMember(Name = "expiration")] 
    public DateTime expiration { get; set; } 

    [DataMember(Name = "conditions")] 
    public List<object> conditions { get; set; } 

    public S3PolicyDocument() 
    { 
     conditions = new List<object>(); 
    } 
} 

,然後填充它是這樣的:

S3PolicyDocument policyDoc = new S3PolicyDocument(); 
policyDoc.expiration = DateTime.Now.AddHours(1); 
S3Bucket bucket = new S3Bucket(); 
bucket.bucket = "followThru"; 
S3acl acl = new S3acl(); 
acl.acl = "private"; 
S3success_action_redirect sar = new S3success_action_redirect(); 
sar.success_action_redirect = ""; 

policyDoc.conditions.Add(bucket); 
policyDoc.conditions.Add(new string[] { "starts-with", "$key", "uploads/" }); 
policyDoc.conditions.Add(acl); 
policyDoc.conditions.Add(sar); 
policyDoc.conditions.Add(new string[] { "starts-with", "$Content-Type", "" }); 

但是我可以用DataContractJsonSerializer不序列化此。我如何在C#中構建它?

或者只是粘貼,作爲一個常量字符串,我不能格式化正確......如果是這樣的解決方案,我將如何粘貼它作爲一個字符串,不把一切在一行... IE瀏覽器這不工作:

string PolicyDoc = "{ 
    \"expiration\": \"" + DateTime.Now.ToString() + "\", 
    \"conditions\": [ 
    {\"bucket\": \"s3-bucket\"}, 
    [\"starts-with\", \"$key\", \"uploads/\"], 
    {\"acl\": \"private\"}, 
    {\"success_action_redirect\": \"http://baasdf/\"}, 
    [\"starts-with\", \"$Content-Type\", \"\"], 
    [\"content-length-range\", 0, 1048576] 
    ] 
}"; 

回答

1

事實證明,這些值都可以格式化爲數組。所以將課程改爲下面的課程將會有效。

[DataContract] 
public class S3PolicyDocument 
{ 
    [DataMember(Name = "expiration")] 
    public string expiration { get; set; } 

    [DataMember(Name = "conditions")] 
    public List<string[]> conditions { get; set; } 

    public S3PolicyDocument() 
    { 
     conditions = new List<string[]>(); 
    } 
} 

填充類,像這樣:

S3PolicyDocument policyDoc = new S3PolicyDocument(); 
policyDoc.expiration = DateTime.Now.AddHours(1).ToUniversalTime().ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'"); 
policyDoc.conditions.Add(new string[] { "eq", "$bucket", "apples" }); 
policyDoc.conditions.Add(new string[] { "starts-with", "$key", "uploads/" }); 
policyDoc.conditions.Add(new string[] { "starts-with", "$acl", "private" }); 
policyDoc.conditions.Add(new string[] { "starts-with", "$success_action_redirect", "" });