【发布时间】:2017-05-03 09:52:42
【问题描述】:
我正在寻找一种干净的方法来使用 AutoMapper 将我的 JSON 响应包装到 JSON 对象中的对象列表(对不起,如果我不清楚,我不确定我想要的操作的正确名称是什么做的是)
这是我的端点的样子:
[HttpGet]
public IHttpActionResult GetDevices()
{
var deviceDtos = _context.Devices.ToList()
.Select(Mapper.Map<Device, DeviceDto>);
return Ok(deviceDtos);
}
这是我的设备映射配置文件的样子:
public MappingProfile()
{
Mapper.CreateMap<Device, DeviceDto>();
Mapper.CreateMap<DeviceDto, Device>();
}
这是我目前得到的:
[
{
"$id": "1",
"id": "abc",
"name": "abc1",
"deviceTypeName": "abc",
"lastSeen": abc,
"contactLost": abc,
"contactLostTime": abc,
"isRegistered": abc,
"dataCollectorId": "abc",
"dataCollectorName": "abc",
"locationId": "abc",
"locationName": "abc"
},
]
但我想要的是:
{
"Devices" :
[
{
"$id": "1",
"id": "abc",
"name": "abc1",
"deviceTypeName": "abc",
"lastSeen": abc,
"contactLost": abc,
"contactLostTime": abc,
"isRegistered": abc,
"dataCollectorId": "abc",
"dataCollectorName": "abc",
"locationId": "abc",
"locationName": "abc"
},
]
}
我浏览过类似的帖子,他们建议使用 JSONConvert.Serialize(new{Device = device}),但是当我这样做时,格式要么消失,要么得到 \n \r,或者如果我使用 Formatting.None该对象不再包装在 Device JSON 对象中。
我也看过了:Automapper:Converting JSON to list of objects
但我无法用我正在做的事情来完成这项工作。
我尝试过使用 JsonObject(Title = "Devices") 但没有显示。
我可以在我的 CreateMap() 中添加一些东西来实现这一点吗?
如果您觉得需要其他代码/信息,我很乐意提供。 提前谢谢你
【问题讨论】:
标签: c# asp.net json automapper