System.Text.Json 字典反序列化为带有引用 id 的构造函数参数

问题描述 投票:0回答:1

我正在使用 .net 8 并尝试使用以 Dictionary 作为参数的 JSONConstructor 反序列化一个类。 但这总是因以下错误而失败:

反序列化构造函数参数时不支持引用元数据。

我认为这是因为 Json 中的引用 id:

  "MyClass": {
    "$id": "3",
    "$type": "MyClassType",
    "MyDictionary": {
      "$id": "4",
      "aaaa": 5661,
      "bbbbb": 5661
    }
  }

这是我的课:

public Dictionary<string, int> MyDictionary{ get; set; } = new();

[JsonConstructor]
private MyClass(Dictionary<string, int> MyDictionary)
{
    this.MyDictionary= MyDictionary;
    //...doing some other setup stuff
}

有没有办法在不编写自定义转换器的情况下处理这个问题?

如果我不使用:

ReferenceHandler = ReferenceHandler.Preserve

这部分有效,但对于我的项目,我需要保留参考资料。

c# json serialization deserialization system.text.json
1个回答
0
投票

您的思路是正确的,因为 $ 代表元数据,而不是实际的数据字段。但修复方法其实就是这样做:

JsonSerializerSettings settings = new JsonSerializerSettings
{
    MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
};

将元数据处理设置为忽略,然后您可以使用 PropertyName 属性序列化/反序列化属性:

[JsonProperty(PropertyName = "$id")]
public string Id { get; set; }

这是示例代码:

internal class Program
{
    static void Main(string[] args)
    {
        var str = @"{
            '$id': '3',
            '$type': 'MyClassType',
            'MyDictionary': {
              '$id': 4,
              'aaaa': 5661,
              'bbbbb': 5661
            }
        }";

        JsonSerializerSettings settings = new JsonSerializerSettings
        {
            MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
        };
        var example = JsonConvert.DeserializeObject<MyClass>(str, settings);
        Console.ReadLine();
    }
}


public class MyClass
{
    [JsonProperty(PropertyName = "$id")]
    public string Id { get; set; }

    [JsonProperty(PropertyName = "$type")]
    public string Type { get; set; }

    public Dictionary<string, int> MyDictionary { get; set; }

    [JsonConstructor]
    public MyClass(string id, string type, Dictionary<string, int> dictionary)
    {
        Id = id;
        Type = type;
        MyDictionary = dictionary;
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.