根据类型反序列化json字符串 [英] deserialize json string depending on type

查看:260
本文介绍了根据类型反序列化json字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Having json strings like this (I have no control over the publisher):

{
  "TypeName": "Type1"
}

{
  "TypeName": "Type1"
}

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

Is this an acceptable way to deserialize the json strings dynamically?:

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 转换器实现和此布局:

You can try with JsonSubtypes converter implementation and this layout:

    [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";
        /* ... */
    }

这篇关于根据类型反序列化json字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆