【发布时间】: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