Json反序列化为动态类型(dynamic)

方法(依赖于Newtonsoft.Json):

/// <summary>
/// 反序列化json字符串
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="jsonText"></param>
/// <returns></returns>
public static T FromJson<T>(string jsonText)
{
    var json = new JsonSerializer
    {
        NullValueHandling = NullValueHandling.Ignore,
        ObjectCreationHandling = ObjectCreationHandling.Replace,
        MissingMemberHandling = MissingMemberHandling.Ignore,
        ReferenceLoopHandling = ReferenceLoopHandling.Ignore
    };

    var sr = new StringReader(jsonText);
    var reader = new JsonTextReader(sr);
    var result = (T)json.Deserialize(reader, typeof(T));
    reader.Close();

    return result;
}
string jsonData = "{\"column\":\"1\"}";//,\"rows\":\"4\"
dynamic jsonObj = JsonHelper.FromJson<dynamic>(jsonData);
string rows = jsonObj.rows;//不会报错 结果为null
Console.WriteLine(rows);
Console.ReadKey();

 

posted @ 2018-12-27 15:35  zhyue93  阅读(1190)  评论(0编辑  收藏  举报