C# Newtonsoft.Json反序列化为dynamic对象之后的使用

通过Newtonsoft.Json将一个json类型的字符串反序列化为dynamic后直接使用报错

源代码:

namespace ConsoleApplication1
{

    class Program
    {
        static void Main()
        {
            var data = "{\"C_Describe\":\"测试\",\"FY_Subtitle\":\"测试\",\"MAX_ZJ\":20000,\"HType\":\"WFB\",\"communityID\":\"28075\",
              \"FY_id\":110352,\"areaID\":11,\"IsPublisher\":\"0\",\"attURL\":\"\"}
"; dynamic jsonData = FromJson<dynamic>(data); if (ContainChinese(jsonData.FY_Subtitle_CN)) Console.WriteLine("1"); if (ContainChinese((dynamic)jsonData.FY_Subtitle)) Console.WriteLine("2"); Console.ReadKey(); } /// <summary> /// 判断是否包含中文 /// </summary> /// <param name="CString"></param> /// <returns></returns> public static bool ContainChinese(string CString) { return Regex.IsMatch(CString??"", @"[\u4e00-\u9fbb]"); } /// <summary> /// 将json字符串反序列化为dynamic类型 /// </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; } } }

解决方法

在调用通过json反序列化的dynamic对象时,要先强制转换为对应的类型

代码:

if (ContainChinese((jsonData.FY_Subtitle_CN ?? "").ToString()))
    Console.WriteLine("1");
if (ContainChinese((jsonData.FY_Subtitle ?? "").ToString()))
    Console.WriteLine("2");

 

转载于:https://www.cnblogs.com/zhyue93/p/json_dynamic_1.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值