I'm looking for a clean way to wrap my JSON responses to a list of objects within an JSON object using AutoMapper(Sorry if I'm unclear, I'm not sure what the correct name of the action I want to do is)
This is what my endpoint looks like:
[HttpGet]
public IHttpActionResult GetDevices()
{
var deviceDtos = _context.Devices.ToList()
.Select(Mapper.Map<Device, DeviceDto>);
return Ok(deviceDtos);
}
This is what my Mappingprofile for device looks like:
public MappingProfile()
{
Mapper.CreateMap<Device, DeviceDto>();
Mapper.CreateMap<DeviceDto, Device>();
}
This is what I currently get:
[
{
"$id": "1",
"id": "abc",
"name": "abc1",
"deviceTypeName": "abc",
"lastSeen": abc,
"contactLost": abc,
"contactLostTime": abc,
"isRegistered": abc,
"dataCollectorId": "abc",
"dataCollectorName": "abc",
"locationId": "abc",
"locationName": "abc"
},
]
But what I want is:
{
"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"
},
]
}
I have looked through similar posts, and they suggest using JSONConvert.Serialize(new{Device = device}), but when I do this the format either dissapears or I get \n \r, or if I use Formatting.None the object is no longer wrapped inside a Device JSON object.
I've also looked through: Automapper:Converting JSON to list of objects
But I'm not able to make this work with what I'm doing.
I've tried using JsonObject(Title = "Devices") but that doesn't show.
Can I add something to my CreateMap() that makes this possible?
If you feel like you need additional code/information I'd be happy to supply it. Thank you in advance