首页 > 解决方案 > 以 json 格式将对象列表保存到 blob

问题描述

我正在 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"  
  }
]
  1. 有没有办法在不先将文件保存在本地驱动器上的情况下保存到我的 blob?
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 的格式错误,创建的新对象是一个新数组,如何上传这个文件而不在我的本地驱动器上保存副本?

标签: c#jsonazureazure-blob-storageazure-table-storage

解决方案


您可以为您的用例使用 Azure 表(这里有一个很棒的示例教程)。基本上,您无需先将数据转换为 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 现在具有 thePartitionKeyRowKey属性的原因。

这两个属性的组合为 Azure 表中的每一行创建了唯一标识符。

如果您还有其他问题,请告诉我。:)


推荐阅读