我试图序列化策略文档,以便开始使用Amazon Web Services 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]
]
}";
答案 0 :(得分: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", "" });