首页 > 解决方案 > 将 C# 对象转换为 DynamoDB json

问题描述

我有 C# 对象

Step1Members step1Members = new Step1Members()
                    {                            
                        businessName =  "Test business",
                        contactName = "Test User"
                    };

我想将 step1Members 转换为 DynamoDB json,如下所示。

{“businessName”:{“S”:“测试业务”},“contactName”:{“S”:“测试用户”}}

请帮助我。

标签: c#jsonamazon-dynamodb

解决方案


您实际上可以使用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类,它基本上是一个字典。


推荐阅读