简体   繁体   中英

C# serialize DynamoDB item to JSON

In my C# lambda I retrieve an item from DynamoDB. It is returned as a Dictionary<string, AttributeValue> . Is there a good way to serialize that to JSON?

The AttributeValue class exposes a bunch of properties to retrieve values of different types. 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.

I want it to recognize a map and turn it into a JSON object, recognize a list and turn it into a JSON list. Basically, I want the object the Item represents.

You can use an alternate approach in C# to connect to DynamoDB using the DocumentModel. This DocumentModel has a ToJson() function.

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 .

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

var json = JsonConvert.SerializeObject(item);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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