【问题标题】:Save list of objects to blob in json format以 json 格式将对象列表保存到 blob
【发布时间】:2019-12-21 19:29:24
【问题描述】:

我正在用 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 的格式错误,创建的新对象是一个新数组,如何上传这个文件而不在我的本地驱动器上保存副本?

【问题讨论】:

  • 您使用 Blob 存储而不是 Azure 表是否有原因?我不确定是什么导致您的 JSON 显示为列表列表,但我建议切换到 Json.NET 并查看是否重现。
  • 我刚刚切换到 Json.NET 并且得到了相同的输出。我从未使用过 Azure 表,这就是我考虑使用 blob 的原因。
  • Azure 表将允许您存储信息而无需将其转换为 JSON 并通过不同的属性进行查询。让我知道您喜欢哪种方法,我将添加一些演示代码作为答案。
  • 看起来不错,我可以试试这些表。我创建对象的方式是否保持不变?

标签: c# json azure azure-blob-storage azure-table-storage


【解决方案1】:

您可以将 Azure Tables (Here is a great tutorial with examples) 用于您的用例。 基本上,您无需先将数据转换为 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 表中的每一行创建了唯一标识符。

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

【讨论】:

    猜你喜欢
    • 2012-09-19
    • 2019-04-18
    • 2020-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-23
    • 2013-10-22
    • 2014-08-30
    相关资源
    最近更新 更多