c# - 如何从 DynamoDb 获取所需格式的对象
问题描述
我有ASP.Net Core
(C#
)应用程序DynamoDb
作为数据库下面是我的函数的样子: -
public async Task<object> GetEvent(string eventId)
{
try
{
var req = new QueryRequest()
{
TableName = _tableName,
KeyConditionExpression = "EventId = :v_Id",
ExpressionAttributeValues = new Dictionary<string, AttributeValue>()
{
{ ":v_Id", new AttributeValue()
{
S = eventId
} },
{
":v_isDeletedFlag",new AttributeValue()
{
BOOL = false
}
}
},
FilterExpression = "IsDeleted = :v_isDeletedFlag",
Limit = 1,
};
var res = await _dynamoClient.QueryAsync(req);
if (res.HttpStatusCode == System.Net.HttpStatusCode.OK)
{
return res.Items;
}
else
{
throw new Exception("No such event found");
}
}
catch (Exception ex)
{
throw;
}
}
但上述方法返回的对象如下:-
[
{
"CreatedOn": {
"b": null,
"bool": false,
"isBOOLSet": false,
"bs": [],
"l": [],
"isLSet": false,
"m": {},
"isMSet": false,
"n": null,
"ns": [],
"null": false,
"s": "Friday,16 August 2019 14.33.35",
"ss": []
},
"IsAlcoholAllowed": {
"b": null,
"bool": false,
"isBOOLSet": true,
"bs": [],
"l": [],
"isLSet": false,
"m": {},
"isMSet": false,
"n": null,
"ns": [],
"null": false,
"s": null,
"ss": []
},
"Description": {
"b": null,
"bool": false,
"isBOOLSet": false,
"bs": [],
"l": [],
"isLSet": false,
"m": {},
"isMSet": false,
"n": null,
"ns": [],
"null": false,
"s": "Hello Events",
"ss": []
},
"Title": {
"b": null,
"bool": false,
"isBOOLSet": false,
"bs": [],
"l": [],
"isLSet": false,
"m": {},
"isMSet": false,
"n": null,
"ns": [],
"null": false,
"s": "Test Event Mumbai",
"ss": []
}}]
但我想要的是具有如下键和值的对象
[
{
"CreatedOn": "Friday,16 August 2019 14.33.35",
"IsAlcoholAllowed": false,
"Description": "Hello Events"
}]
我怎样才能得到这个?
谢谢!
解决方案
如果我正确理解您的问题,那么您正在使用 Dynamo 的低级编程模型查询数据,这就是为什么您会获得描述每个属性的详细 JSON 的原因。
如果您想更好地控制您的响应,如何使用 DynamoDB 的对象持久性编程模型?
定义一个代表您的文档的模型:
[DynamoDBTable("Events")]
public class Event
{
[DynamoDBHashKey]
public int EventId { get; set; }
public DateTime CreatedOn { get; set; }
public bool IsAlcoholAllowed { get; set; }
public string Description { get; set; }
public bool IsDeleted { get; set; }
}
然后通过以下方式查询:
var client = new AmazonDynamoDBClient();
var context = new DynamoDBContext(client);
var filter = new QueryFilter();
filter.AddCondition(Model.HashKey, QueryOperator.Equal, 123);
var events = await context.FromQueryAsync<Event>(new QueryOperationConfig
{
Select = SelectValues.AllAttributes,
Filter = filter
});
然后,您可以在 JSON 解析器中传递此模型的列表,从而使您更接近目标数据结构。
推荐阅读
- python - numpy 的 memmap 写时复制模式是如何工作的?
- python - 通过 for 循环进行第二次迭代时出现“熊猫”错误
- php - symfony4 在表单中注入参数
- c# - 尝试使用 c# 从 wsdl 获取数据
- django - Django 反向关系序列化器
- json - 离子读取本地 JSON 文件
- php - 如何通过 PHP CURL POST 上传文件
- javascript - 用于书签的 Chrome 扩展 API
- reactjs - 如何防止 Visual Studio 代码在我的 JSX 中放置换行符?
- reporting-services - SSRS 无法识别条形码表达式中的数据集