我正在用C#创建对象列表。我想将它们以适当的JSON格式保存在Blob存储容器中。目前,我将它们保存在本地驱动器上,然后上传到Blob。我面临的两个问题: 1.当我添加新对象时,Json格式如下:
[
{
"id": "1",
"Name": "Peter",
"Surname": "Pan"
}
]
[
{
"id": "2",
"Name": "Steve",
"Surname": "Pan"
}
]
如何更新我的代码以使它们成为一个带有逗号分隔值的数组?
[
{
"id": "1",
"Name": "Peter",
"Surname": "Pan"
},
{
"id": "2",
"Name": "Steve",
"Surname": "Pan"
}
]
List<Obj> list= new List<Obj>();
list.Add(new Obj()
{
Id = "1",
Name = "Peter",
Surname = "Pan"
});
// Serialize to JSON output
var serializer = new JavaScriptSerializer();
var serializedResult = serializer.Serialize(list);
// write string to file locally
System.IO.File.AppendAllText(@"people.json", serializedResult);
//Create or overwrite the "myblob" blob with the contents of a local file
using (var fileStream = System.IO.File.OpenRead(@"people.json"))
{
await blockBlob.UploadFromStreamAsync(fileStream);
}
Json out格式错误,创建的新对象是一个新数组,还有如何上传此文件而不将副本保存在本地驱动器上?
答案 0 :(得分:1)
您可以将Azure表(documentation for WebUtility.HtmlEncode
)用于您的用例。
基本上,您将保存数据而无需先将其转换为JSON,并且能够查询和更新特定数据而无需重新上传整个文件。
根据教程示例和您的代码,您需要执行以下操作:
CloudStorageAccount storageAccount = new CloudStorageAccount(
new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials(
"<name>", "<account-key>"), true);
// Create the table client.
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
// Get a reference to a table named "peopleTable"
CloudTable peopleTable = tableClient.GetTableReference("peopleTable");
await peopleTable.CreateIfNotExistsAsync();
TableBatchOperation batch = new TableBatchOperation();
batch.Add(TableOperation.InsertOrReplace(new Obj()
{
PartitionKey = "1",
RowKey = "<SomeOtherIdentifier>",
Name = "Peter",
Surname = "Pan"
}));
IList<TableResult> results = await peopleTable.ExecuteBatchAsync(batch);
// Do what you have to do with the results
非常重要说明:
您的模型(在这种情况下为Obj)必须实现接口ITableEntity
,或仅从EntityEntity
对象派生。
这就是为什么您的Obj现在拥有PartitionKey
和RowKey
属性的原因。
这两个属性的组合为Azure表中的每一行创建了唯一标识符。
让我知道您是否还有其他问题。 :)