.NET Core 6.0 C#:如何处理DynamoDB嵌套DynamoDBEntry?
处理DynamoDB嵌套结构的正确方法
你原来的代码触发异常的核心原因是doc["dimensions"].ToJson()返回的是JSON字符串,而非可直接通过索引器访问的JObject,后续直接用dimension["length"]["N"]会因为字符串没有索引器而抛出异常。
以下是两种可行的正确处理方案:
方案一:利用AWS SDK原生Document类型处理(推荐)
DynamoDB的Document本身支持嵌套结构访问,直接将嵌套字段转换为Document类型即可,无需额外JSON解析:
if (doc.ContainsKey("dimensions") && doc["dimensions"] is Document dimensionDoc) { // 处理length属性 if (dimensionDoc.TryGetValue("length", out AttributeValue lengthAttr) && !string.IsNullOrEmpty(lengthAttr.N) && decimal.TryParse(lengthAttr.N, out decimal length)) { product.Length = length; } // 处理width属性 if (dimensionDoc.TryGetValue("width", out AttributeValue widthAttr) && !string.IsNullOrEmpty(widthAttr.N) && decimal.TryParse(widthAttr.N, out decimal width)) { product.Width = width; } // 处理weight属性 if (dimensionDoc.TryGetValue("weight", out AttributeValue weightAttr) && !string.IsNullOrEmpty(weightAttr.N) && decimal.TryParse(weightAttr.N, out decimal weight)) { product.Weight = weight; } // 处理height属性 if (dimensionDoc.TryGetValue("height", out AttributeValue heightAttr) && !string.IsNullOrEmpty(heightAttr.N) && decimal.TryParse(heightAttr.N, out decimal height)) { product.Height = height; } }
说明:
doc["dimensions"]如果是嵌套结构,本质是Document类型,直接用is关键字做类型判断即可避免类型错误AttributeValue是DynamoDB存储数据的原生类型,其中N字段对应数值类型的字符串表示- 增加
!string.IsNullOrEmpty(lengthAttr.N)判断,避免空字符串解析失败
方案二:通过Json.NET解析JSON字符串
如果坚持用JSON解析,需要先将ToJson()返回的字符串反序列化为JObject,再进行索引访问:
if (doc.ContainsKey("dimensions") && doc["dimensions"] is not DynamoDBNull) { var dimensionJson = doc["dimensions"].ToJson(); var dimensionObj = JsonConvert.DeserializeObject<JObject>(dimensionJson); if (dimensionObj != null) { // 处理length,使用空值传播运算符避免NullReferenceException if (dimensionObj["length"]?["N"] is JToken lengthToken && decimal.TryParse(lengthToken.ToString(), out decimal length)) { product.Length = length; } // 处理width if (dimensionObj["width"]?["N"] is JToken widthToken && decimal.TryParse(widthToken.ToString(), out decimal width)) { product.Width = width; } // 处理weight if (dimensionObj["weight"]?["N"] is JToken weightToken && decimal.TryParse(weightToken.ToString(), out decimal weight)) { product.Weight = weight; } // 处理height if (dimensionObj["height"]?["N"] is JToken heightToken && decimal.TryParse(heightToken.ToString(), out decimal height)) { product.Height = height; } } }
说明:
- 必须先将JSON字符串反序列化为
JObject才能使用索引器 - 使用
?空值传播运算符,避免某个属性不存在时抛出NullReferenceException
内容的提问来源于stack exchange,提问作者khteh
相关产品推荐
相关产品推荐

