sag*_*agg 1 .net api json .net-6.0
我们正在将 API 从 .net 4.8 库移至 .Net 6。我遇到了一个奇怪的问题,即没有任何嵌套对象(成本)被序列化。
我尝试在启动中添加 using,但我的 api 无法使用此选项。我什至看不到启用此选项的控制器。
Newtonsoft.Json.Serialization;
...............
services.AddControllers().AddNewtonsoftJson();
Run Code Online (Sandbox Code Playgroud)
或者
`services.AddControllers().AddNewtonsoftJson(options =>`
`{`
`options.SerializerSettings.ContractResolver = new DefaultContractResolver();`
`options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;`
`});`
services.AddControllers().AddJsonOptions(o =>
{
o.JsonSerializerOptions.MaxDepth = 4;
o.JsonSerializerOptions.PropertyNamingPolicy = null;
o.JsonSerializerOptions.DictionaryKeyPolicy = null;
});
Run Code Online (Sandbox Code Playgroud)
我缺少什么?
我期望以下格式
`{
"Status": 200,
"Message": "Processed Successfully",
"Description": null,
"Errors": null,
"ResponseObject": {
"Costs": [
{
"Component": "xxx",
"Key1": "123",
"Key2": null,
"Key3": null,
"ProductCode": "x",
"From": "2021-08-05T00:00:00",
"To": "2021-08-05T23:59:59",
"Value": "1584",
"CurrencyCode": null,
"UnitOfMeasure": null
},
{
"Component": "X",
"Key1": "123",
"Key2": null,
"Key3": null,
"ProductCode": "Y",
"From": "2021-08-05T00:00:00",
"To": "2021-08-05T23:59:59",
"Value": "3131",
"CurrencyCode": null,
"UnitOfMeasure": null
}
]
}`
Run Code Online (Sandbox Code Playgroud)
C#对象如下:
public class Response
{
public int Status { get; set; }
public string Message { get; set; }
public string Description { get; set; }
public object Errors { get; set; }
public object ResponseObject { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
下面是用于填充对象的代码:
var costsVM = new CostsVM();
var response = new Response();
costsVM.Costs.AddRange(costs);
response.ResponseObject = costsVM;
response.Status = 200;
response.Message = "Processed Successfully";
response.Description = null;
return Ok(response);
Run Code Online (Sandbox Code Playgroud)
成本VM定义如下:
public class CostsVM
{
public List<CostsDTO> Costs = new List<CostsDTO>();
}
public class CostsDTO
{
public string Component { get; set; }
public string? Key1 { get; set; }
public string? Key2 { get; set; }
public string? Key3 { get; set; }
public string ProductCode { get; set; }
public DateTime From { get; set; }
public DateTime To { get; set; }
public string Value { get; set; }
public string? CurrencyCode { get; set; }
public string? UnitOfMeasure { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我似乎找到了解决办法。
我需要在 JsonSerializer 中启用 IncludeFields
services.AddMvc().AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNamingPolicy = null;
options.JsonSerializerOptions.MaxDepth = 64;
options.JsonSerializerOptions.IncludeFields = true;
});
Run Code Online (Sandbox Code Playgroud)