c# - 将 C# 对象转换为 DynamoDB json
问题描述
我有 C# 对象
Step1Members step1Members = new Step1Members()
{
businessName = "Test business",
contactName = "Test User"
};
我想将 step1Members 转换为 DynamoDB json,如下所示。
{“businessName”:{“S”:“测试业务”},“contactName”:{“S”:“测试用户”}}
请帮助我。
解决方案
您实际上可以使用EfficientDynamoDb来做到这一点。
根据您的示例,假设您有一个这样的类:
public class Step1Members
{
[DynamoDbProperty("businessName")]
public string BusinessName { get; set; }
[DynamoDbProperty("contactName")]
public string ContactName { get; set; }
}
为了生成 DynamoDb JSON,您需要:
// Create DynamoDb context, credentials are not required for JSON generation, only for real database calls
var context = new DynamoDbContext(new DynamoDbContextConfig(RegionEndpoint.EUCenteral1, new AwsCredentials("public_key", "private_key")));
var step1Members = new Step1Members()
{
BusinessName = "Test business",
ContactName = "Test User"
};
await using var memoryStream = new MemoryStream();
await using var jsonWriter = new Utf8JsonWriter(memoryStream);
// Convert a class object into the document
var document = context.ToDocument(step1Members);
// Write the document using Utf8JsonWriter
jsonWriter.WriteStartObject();
foreach (var attribute in document)
{
jsonWriter.WritePropertyName(attribute.Key);
attribute.Value.Write(jsonWriter);
}
jsonWriter.WriteEndObject();
jsonWriter.Flush();
// Read the final JSON string from the memory stream
var jsonString = Encoding.UTF8.GetString(memoryStream.ToArray());
如果您不想为每个用例创建一个 C# 类,您可以只使用普通Document
类,它基本上是一个字典。
推荐阅读
- vue.js - 如何在 Vue.js 中即时绑定对象数据的变化?
- redis - 目前支持的redis版本有哪些?(最新稳定版 6.0.6)
- r - “as.POSIXlt.default 中的错误:不知道如何将“x”转换为“POSIXlt”类
- python - 在pyspark中导入多个py文件
- php - 在 php 中创建多个动态下拉过滤器时遇到问题
- c++ - 在保证非 const 分配的情况下将 const 从非静态 const 字段中丢弃是否合法
- http - 有没有办法通过 curl 请求 .mov 文件而无需手动设置 mimetype?
- rust - 与复制类型的借用特征相反?
- html - 网格布局无法对齐
- reactjs - 图像映射以在悬停时获取特定数据图像