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

时间:2023-01-09 17:05:46

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

C# Newtonsoft.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("");
if (ContainChinese((dynamic)jsonData.FY_Subtitle))
Console.WriteLine(""); 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("");
if (ContainChinese((jsonData.FY_Subtitle ?? "").ToString()))
Console.WriteLine("");