C# dynamic json
阅读原文时间:2023年07月11日阅读:2

对应普通对象,写个扩展方法,ToJson蛮方便。

但是 dynamic 类型就不行了,因为是运行时解析,只能转换为强类型 IDictionary 才可以。

配置文件(Firebird):



转换工具:

 static class JsonHelper  
 {  
     public static string ToJson(this object obj)  
     {  
         var str = JsonConvert.SerializeObject(obj, Formatting.Indented, new JsonSerializerSettings  
         {  
             NullValueHandling = NullValueHandling.Ignore,  
             DateFormatString = "yyyy-MM-dd HH:mm:ss",  
             ReferenceLoopHandling = ReferenceLoopHandling.Ignore//循环引用  
         });  
         return str;  
     }

     public static T FromJson<T>(this string json) where T : class  
     {  
         return JsonConvert.DeserializeObject(json, typeof(T), new IsoDateTimeConverter  
         {  
             DateTimeFormat = "yyyy-MM-dd HH:mm:ss"  
         }) as T;  
     }  
 }

Demo:

         var connectionString = ConfigurationManager.ConnectionStrings\["fb"\].ConnectionString;  
         using (var db = new DbContext().ConnectionString(  
             connectionString,  
             new DB2Provider(),  
             FirebirdSql.Data.FirebirdClient.FirebirdClientFactory.Instance))  
         {  
             List<dynamic> users = db.Sql(@"SELECT  

M_USER.ID,
M_USER.CODE,
M_USER.PWD,
M_USER.LABEL,
M_USER.CRE_TIME
FROM
M_USER
where id > @0").Parameters().QueryMany();

             foreach (var user in users)  
             {  
                 var tem = user as IDictionary<string, object>;  
                 Console.WriteLine(tem.ToJson());  
             }  
         }

         Console.ReadLine();

效果: