【问题标题】:How to get deserialize object when type discriminator element on root json object using System.Text.Json使用 System.Text.Json 在根 json 对象上键入鉴别器元素时如何获取反序列化对象
【发布时间】:2020-05-05 02:20:34
【问题描述】:

对不起,我的英语不好。

我成功运行了来自这个doc 的代码。我得到了新的 JSON 数据,还有另一个问题。

JSON 数据定义如下:

{
    "id": 3,
    "title": "aaa",
    "typeDiscriminator": "search",
    "settingDataTemp": {
      "id": 11,
      "type": "11",
      "value": "11"
    }
}

而POCO类定义为:

public class RootContent
{
    public int id { get; set; }
    public string title { get; set; }
    public PageModuleType typeDiscriminator { get; set; }
    public IPageSubContentSetting settingDataTemp { get; set; }
}

我想反序列化settingDataTemp对象,所以JsonConverterRead方法就像

public override IPageSubContentSetting Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
    PageModuleType typeDiscriminator;
    string rawText;
    var discriminatorPropName = nameof(RootContent.typeDiscriminator);

    using (var jsonDocument = JsonDocument.ParseValue(ref reader))
    {
        if (!jsonDocument.RootElement.TryGetProperty(discriminatorPropName, out var typeProperty))
        {
             throw new JsonException();
        }

        var result = Enum.TryParse(typeProperty.GetString(), true, out typeDiscriminator);

        if (!result)
        {
             throw new JsonException();
        }

        rawText = jsonDocument.RootElement.GetRawText();
     }
}

无法从JsonDocument.RootElement 获取typeDiscriminator,因为它是在外部对象上定义的。

有什么方法可以获取typeDiscriminator 的值吗?

【问题讨论】:

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


    【解决方案1】:

    我解决了问题,只需使用 NewtonSoft.Json 编辑 JSON 结构并将 typeDiscriminator 值从根复制到 settingDataTemp 元素。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-06
      • 2020-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多