【问题标题】:How to make a JSON serializer ignore the attributes in the model and deserialize based on the property name如何使 JSON 序列化程序忽略模型中的属性并根据属性名称反序列化
【发布时间】:2023-01-25 18:52:26
【问题描述】:

根据某些条件,我需要将 JSON 字符串反序列化为不同的模型,有时是模型 A,有时是模型 B。但是在模型 A 中有来自 System.Text.Json.SerializationJsonPropertyName 属性,而在类 B 中有来自 @987654325 的 JsonProperty 属性@.问题是 JSON 字符串对应于实际的属性名称,而不是属性中给出的名称。我想让 JSON 序列化器(Newtonsoft 或 System.Text)忽略它自己的属性。那可能吗?

这是一个示例 JSON 字符串:

{
  "PropertyOne" : "some value"
}

这是一个示例模型:

public class A
{
  [JsonProperty("property_one")]
  public string PropertyOne{ get; set; }
}
public class B
{
  [JsonPropertyName("property_one")]
  public string PropertyOne{ get; set; }
}

PS我不能改变模型

【问题讨论】:

  • 我假设 Newtonsoft.Json 将忽略 System.Text.Json 属性,反之亦然,因此您可能需要在反序列化一个类时使用 Newtonsoft,在反序列化另一个类时使用 System.Text.Json。
  • 听起来像是自定义合同解析器的工作。你可以在这里看到一个有点相关的例子:stackoverflow.com/a/20639697/625594

标签: c# .net json.net system.text.json


【解决方案1】:

正如 Sergey Kudriavtsev 在 cmets 部分中所建议的那样,自定义合同解析器非常适合我的用例。我会将解决方案留给有类似问题的任何人。

这是自定义合同解析器类:

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;

namespace mynamespace
{
  public class DefaultNameContractResolver : DefaultContractResolver
  {
    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
    {
      // Let the base class create all the JsonProperties 
      IList<JsonProperty> list = base.CreateProperties(type, memberSerialization);

      // Now inspect each property and replace the name with the real property name
      foreach (JsonProperty prop in list)
      {
        prop.PropertyName = prop.UnderlyingName;
      }
      return list;
    }
  }
}

下面是如何使用它:

string json = "{ "PropertyOne" : "some value" }";
Type recordType = typeof(A);
Newtonsoft.Json.JsonSerializerSettings settings = new()
{
  ContractResolver = new mynamespace.DefaultNameContractResolver()
};
var myObject = Newtonsoft.Json.JsonConvert.DeserializeObject(json, recordType, settings);

【讨论】:

    猜你喜欢
    • 2014-09-30
    • 2013-04-07
    • 2019-08-02
    • 2017-03-07
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多