0

Sorry for my poor English.

I had success run code from this doc. I got new JSON data and there is another problem.

The JSON data is defined like this:

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

And the POCO class is defined as:

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

I want to deserialize settingDataTemp object, so the JsonConverter Read method like

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();
     }
}

Can't get typeDiscriminator from JsonDocument.RootElement because it's defined on outer object.

Is there any way to get typeDiscriminator value?

dbc
  • 104,963
  • 20
  • 228
  • 340

1 Answers1

0

I solved problem just use NewtonSoft.Json To edit JSON struct and copy typeDiscriminator value from root to settingDataTemp element.