c# - 以 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"
}
]
- 有没有办法在不先将文件保存在本地驱动器上的情况下保存到我的 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 的格式错误,创建的新对象是一个新数组,如何上传这个文件而不在我的本地驱动器上保存副本?
解决方案
您可以为您的用例使用 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 现在具有 thePartitionKey
和RowKey
属性的原因。
这两个属性的组合为 Azure 表中的每一行创建了唯一标识符。
如果您还有其他问题,请告诉我。:)
推荐阅读
- javascript - 带有长文本问题的 jQuery tablesorter 2.31.1 可调整大小的表格
- android - 数据绑定在不膨胀的情况下不起作用
- java - 在 @PostConstruct 之后调用 Mockito @Before 方法
- c# - API 控制器查询中间表的存储库模式问题
- database - 使用 Amazon RDS 只读副本时是否可能获得不一致的数据?
- javascript - click 回调根据 var 或 let 丢失上下文
- c++ - 使用 cv::dnn::Layer cv::dnn::LayerFactory 和 cv::dnn::Net 的问题
- java - 由一对多关系引起的休眠堆栈溢出
- visual-studio-code - 片段中的智能感知 (VSCode)
- excel - 如何更正一个公式 tat 有多个返回“#VALUE!”的 IF 语句 当某些单元格未填充时?