我有一个.NET Core Web API项目,我的api操作之一返回了一个格式为JSON的对象。该对象具有3个深度级别,我希望它看起来像这样:
{
"pickupDate": "0001-01-01T00:00:00",
"pickupLocation": {
"address1": null,
"address2": null,
"address3": null,
"cityStateCountry": {
"city": null,
"state": null,
"country": null
},
"zip": null
},
"po": 12345,
"itemNameAndDesc": "BobSled"
}
相反,cityStateCountry
对象只是显示为null
。我使用Postman进行了检查,并使用angular将整个json对象输出到视图中。
{
"pickupDate": "0001-01-01T00:00:00",
"pickupLocation": {
"address1": null,
"address2": null,
"address3": null,
"cityStateCountry": null, //???
"zip": null
},
"po": 12345,
"itemNameAndDesc": "BobSled"
}
据我了解,这是服务器端的问题。为什么.NET Core会这样做,我该如何解决?获取数据的操作如下所示:
// GET: api/Shipments/5
[HttpGet("{id}")]
public async Task<ActionResult<dynamic>> GetShipment(long id)
{
var ship = await _context.Shipments
.Where(c => !c.IsProcessed)
.Select(c => new
{
c.PO,
c.ItemNameAndDesc
})
.FirstOrDefaultAsync(c => c.PO == id);
if (ship == null)
{
return null;
}
var shipmentformviewmodel = new ShipmentFormViewModel()
{
PickupDate = new DateTime(),
PickupLocation = new PickupLocation(),
PO = ship.PO,
ItemNameAndDesc = ship.ItemNameAndDesc
};
return shipmentformviewmodel;
}
答案 0 :(得分:0)
因此不确定是否将其归类为“变通方法”或实际解决方案,但是cityStateCountry
对象实际上是null
(它的成员均未初始化),所以如果我继续.NET端并实际上初始化这些变量(无论是在操作中还是在构造函数中),我实际上可以看到json对象的所有级别,如下所示:
{
"pickupDate": "0001-01-01T00:00:00",
"pickupLocation": {
"address1": null,
"address2": null,
"address3": null,
"cityStateCountry": {
"city": "",
"state": "",
"country": ""
},
"zip": null
},
"po": 12345,
"itemNameAndDesc": "BobSled"
}
根据要求,空字符串和null
可能意味着同一件事(对我而言,这是事实)。
答案 1 :(得分:0)
Null字段不会自动放置在Json上。您必须对StartUp类中的ConfigureServices进行此更改:
services.AddMvc(option =>
{
option.OutputFormatters.RemoveType(typeof(HttpNoContentOutputFormatter));
option.OutputFormatters.Insert(0, new HttpNoContentOutputFormatter
{
TreatNullValueAsNoContent = false
});
});