通過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");
