我有一个具有以下形式的JSON:
{
"type": "oneOfMyTypes",
"body": {
//object corresponding to the type, contains some key-value pairs"
}
}body对象的结构取决于类型。因此,我想读取类型,检查它是否是我预定义的类型之一,打开类型并根据类型将主体解析为不同的对象。身体对象可以是非常不同的,我不想让一个“超级身体”对象包含所有可能的属性。我还想使用JSON,我不想使用任何二进制格式。
问题:如何使用System.Text.Json或Utf8Json实现这一点?
到目前为止,我已经找到了JsonDocument+JsonElement和Utf8JsonReader。在知道了类型之后,我将知道主体的适当类,所以我想对主体使用一种简单的解析技术,例如使用JsonSerializer.Deserialize。
在这里回答了:Is polymorphic deserialization possible in System.Text.Json?
发布于 2020-10-17 14:12:37
假设您使用的是Newtonsoft.Json:
序列化时,请使用TypeNameHandling.Auto设置。这也指示序列化程序保存对象的类型。反序列化时,这种类型的“body”对象将被重构。
var json = JsonConvert.SerializeObject(testResults,
Formatting.Indented,
new JsonSerializerSettings {
TypeNameHandling = TypeNameHandling.Auto
});另见:https://www.newtonsoft.com/json/help/html/SerializeTypeNameHandling.htm
发布于 2020-10-17 15:00:13
如果您可以使用Json.net (更灵活得多),那么您可以为此目的使用JObject:
//First, parse the json as a JObject
var jObj = JObject.Parse(json);
//Now switch the type
switch(jObj["type"].ToString())
{
case "oneOfMyTypes":
var oneType = jObj["body"].ToObject<oneOfMyTypes>();
//process it as you need
break;
case "otherOfMyTypes":
var otherType = jObj["body"].ToObject<otherOfMyTypes>();
//process it...
break;
//...
//unsupported type
default:
throw new InvalidDataException("Unrecognized type");
}https://stackoverflow.com/questions/64403317
复制相似问题