gpt4 book ai didi

c# - 根据类型反序列化json字符串

转载 作者:行者123 更新时间:2023-11-30 17:39:42 25 4
gpt4 key购买 nike

有这样的 json 字符串(我无法控制发布者):

{
"TypeName": "Type1"
}

{
"TypeName": "Type1"
}

这是动态反序列化 json 字符串的可接受方式吗?:

public class DeserializationFactory
{
public static IPoco GetEvent(string jsonString)
{
var o = JObject.Parse(jsonString);
IPoco poco = null;
switch (o["TypeName"].ToString())
{
case "Type1":
poco = JsonConvert.DeserializeObject<Type1>(jsonString);
break;

case "Type2":
poco = JsonConvert.DeserializeObject<Type2>(jsonString);
break;
}
return poco;
}
}

最佳答案

你可以试试JsonSubtypes转换器实现和此布局:

    [JsonConverter(typeof(JsonSubtypes), "TypeName")]
[JsonSubtypes.KnownSubType(typeof(Type1), "Type1")]
[JsonSubtypes.KnownSubType(typeof(Type2), "Type2")]
public interface IPoco
{
string TypeName { get; }
}

public class Type1 : IPoco
{
public string TypeName { get; } = "Type1";
/* ... */
}

public class Type2 : IPoco
{
public string TypeName { get; } = "Type2";
/* ... */
}

关于c# - 根据类型反序列化json字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35182949/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com