简体   繁体   English

C#将DynamoDB项目序列化为JSON

[英]C# serialize DynamoDB item to JSON

In my C# lambda I retrieve an item from DynamoDB. 在C#lambda中,我从DynamoDB中检索了一个项目。 It is returned as a Dictionary<string, AttributeValue> . 它以Dictionary<string, AttributeValue> Is there a good way to serialize that to JSON? 有什么好方法可以将其序列化为JSON吗?

The AttributeValue class exposes a bunch of properties to retrieve values of different types. AttributeValue类公开了一堆属性以检索不同类型的值。 If you do a simple serialization each one of those properties shows up in the JSON, most of them null, and makes a really messy object. 如果执行简单的序列化,那么这些属性中的每个属性都会显示在JSON中,其中大多数属性都为null,并形成一个真正混乱的对象。

I want it to recognize a map and turn it into a JSON object, recognize a list and turn it into a JSON list. 我希望它识别地图并将其变成JSON对象,识别列表并将其转变为JSON列表。 Basically, I want the object the Item represents. 基本上,我想要Item代表的对象。

You can use an alternate approach in C# to connect to DynamoDB using the DocumentModel. 您可以在C#中使用另一种方法来使用DocumentModel连接到DynamoDB。 This DocumentModel has a ToJson() function. 该DocumentModel具有ToJson()函数。

Table table = Table.LoadTable(client, "yourtable");
Document document = table.GetItem(123);
string strJSON = document.ToJson();

May as well post this as an answer. 也可以将其发布为答案。

You can convert an object to json by using the Newtonsoft.Json library: https://www.newtonsoft.com/json . 您可以使用Newtonsoft.Json库将对象转换为json: https ://www.newtonsoft.com/json。

var item = new Dictionary<string, AttributeValue>();

var json = JsonConvert.SerializeObject(item);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM