【问题标题】:i am receiving an error while returning `<IEnumerable<RiskValue>`.. ASP.NET [closed]我在返回 `<IEnumerable<RiskValue>` 时收到错误 .. ASP.NET [关闭]
【发布时间】:2021-04-26 07:09:58
【问题描述】:
var result = JsonConvert.DeserializeObject<Risks>(jsonData);
             var finalResult = result.Value.Where(x => x.ID == 5).ToList();
             return finalResult;
    

我正在开发一个返回 &lt;IEnumerable&lt;RiskValue&gt; 的 API,反序列化不会导致任何错误,当我返回最终结果时会显示此错误,知道是什么原因造成的吗?

System.InvalidOperationException: The JSON property name for 'HRDF_1.Models.RisksValue.ID' collides 
with another property.

System.InvalidOperationException: The JSON property name for 'test_1.Models.RisksValue.ID' collides with another property.
   at System.Text.Json.ThrowHelper.ThrowInvalidOperationException_SerializerPropertyNameConflict(Type type, JsonPropertyInfo jsonPropertyInfo)

【问题讨论】:

  • 嗨@someone,你能分享你的模型设计吗?错误消息似乎表明您的模型包含两个相同名称的属性?
  • 我在模型中有public int Id { get; set; }public string ID { get; set; }
  • 发表评论,因为我无法给出答案:在我的例子中,我有两个同名的属性,子类覆盖了基类。我选择重命名父类的属性并避免对其进行序列化,以解决此问题/错误。

标签: c# json asp.net-core


【解决方案1】:

尝试在 Startup.cs 中将 PropertyNameCaseInsensitive 设置为 false

services.AddControllers().AddJsonOptions(options => { 
    options.JsonSerializerOptions.PropertyNamingPolicy = null; 
    
    //the importance here..
    options.JsonSerializerOptions.PropertyNameCaseInsensitive = false;
});

【讨论】:

  • 只是关于 OP 问题的注释:模型很重要——如果“Id”和“ID”在概念上不同,那么它们应该得到不同的名称。如果无法访问修改模型,我建议使用包装/转换层。
猜你喜欢
  • 1970-01-01
  • 2012-05-17
  • 2014-07-22
  • 2011-03-11
  • 1970-01-01
  • 1970-01-01
  • 2015-03-22
  • 2016-08-23
  • 2021-04-13
相关资源
最近更新 更多