动态分配类型的泛型属性类型



我期待JSON对象从一个API,就像:

{
"header":{
"message_type":"message_type",
"notification_type":"notification_type"
},
"body":{
"id":"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"related_entity_type":"inbound_funds",
}
}

问题是body可以有任意数量和类型的props。而且,我有相应的c#模型为每一个身体类型。有没有有效的方法来解析和反序列化这些对象到相关的c#模型,动态的?

我试过了,bus then Body在运行时没有除菌。

public class PushNotification : Body
{
[JsonProperty("header")]
public Header Header { get; set; }
[JsonProperty("body")]
public Body Body { get; set; }
}
public class Body
{
}

作为一种替代方法,您可以使用Newtonsoft中的JObject。解析动态Json。它可以使用键值对

从JObject中读取。
JObject jsonString= JObject.Parse(inputJson);
var id=jsonString["body"]["id"];

感谢大家花时间帮助我解决这个问题。耶根·玛丽亚,塞尔文和约翰!!

我设法解决它使用动态类型和工厂!

下面是代码示例

API层:

using var reader = new StreamReader(Request.Body, Encoding.UTF8);
var content = await reader.ReadToEndAsync();
var data = (JObject)JsonConvert.DeserializeObject(content)!;
var message_Type = data.SelectToken("header.message_type")!.Value<string>()!;
_factory.Type = message_Type;
var notification = _factory.CreateNotificationType();
var dynamicObject = JsonConvert.DeserializeObject<dynamic>(content)!;

notification = dynamicObject.ToObject(notification.GetType());

return Ok(notification);

下面是工厂方法:

public class PushNotificationFactory : IPushNotificationFactory

{公共字符串类型{获取;设置;}

public dynamic CreateNotificationType()
{        
var type = Type switch
{
"cash_manager_transaction" => new PushNotification<CashManagerTransaction>(),
_ => throw new NotImplementedException(),
};
return Activator.CreateInstance(type.GetType());
}

}

最新更新