【问题标题】:ASP.NET How do I use Automapper to wrap JSON to return a list of JSON Objects with root nameASP.NET 如何使用 Automapper 包装 JSON 以返回具有根名称的 JSON 对象列表
【发布时间】: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


    【解决方案1】:

    AutoMapper 配置无关。您只需要将列表包装在一个对象中。您可以为此使用匿名类

    return Ok(new {Devices = deviceDtos});
    

    或者您可以创建包装类并返回该类的实例

    public class DevicesReponse
    {
        public List<DeviceDto> Devices { get; set; }
    }
    

    并使用您的包装类作为响应

    var response = new DevicesResponse { Devices = devicesDtos };
    return Ok(response);
    

    【讨论】:

    • 你是救生员!有没有办法在 DTO 上放置一个属性,这样我就可以在不创建自定义包装类的情况下设置对象的名称?我试过使用 [JsonObject(Title = "devices")] 但它仍然显示 "deviceDto"。
    • 你有List的对象,所以你不能放任何属性来包装它,或者你需要使用自己的列表类并在上面放一个属性。在我看来,创建包装类会更好
    • 好的,我会尝试使用包装类。我应该返回 Ok(new{WrapperClass = deviceDtos}) 还是在使用包装类时我的返回语句应该不同?再次感谢您
    • 不,您需要将包装类的实例传递给Ok 方法。我添加了一个例子来回答
    • 有效!十分感谢你的帮助。我想我认为必须有一个内置的解决方案来使这更容易,但我认为这是最好的方法。再次感谢您。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-06
    • 2013-03-18
    • 2016-06-11
    • 2012-09-26
    相关资源
    最近更新 更多