C#中的部分和动态JSON反序列化

问题描述

我有一个具有以下格式的JSON:

{
   "type": "oneOfMyTypes","body": {
       //object corresponding to the type,contains some key-value pairs"
   }
}

主体对象的结构取决于类型。因此,我想读取类型,检查它是否是我的预定义类型之一,打开该类型,然后根据类型将正文解析为另一个对象。 主体对象可以有很大的不同,我不想创建一个包含所有可能属性的“超级主体”对象。我也想使用JSON,并且我不想使用任何二进制格式。

问题: 如何使用System.Text.JsonUtf8Json来实现?

到目前为止,我已经找到了JsonDocument + JsonElement和Utf8JsonReader。知道类型之后,我将知道适合于主体的类,因此我想对主体使用简单的解析技术,例如使用JsonSerializer.Deserialize。

在此处回答Is polymorphic deserialization possible in System.Text.Json?

解决方法

假设您正在使用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

,

如果可以使用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");

}