1.如果T类型里面的字段数量 大于 json字符串里面实际的字段数,这个可以成解析么?
解析结果又是怎样呢?
2.这个反序列化 是否 大小写敏感呢?
给你个封装,里面实现了字段名全转成小写
public static class JsonHelper { /// <summary> /// 转化成JSON /// </summary> /// <param name="value">对象或值</param> /// <returns></returns> public static string ToJson(this object value) { return JsonConvert.SerializeObject(value); } /// <summary> /// 转化成JSON-可配置 /// </summary> /// <param name="value">对象或值</param> /// <param name="jsonSetting">Json.NET配置项</param> /// <returns></returns> public static string ToJson(this object value, JsonSerializerSettings jsonSetting) { return JsonConvert.SerializeObject(value, jsonSetting); } /// <summary> /// 转化成JSON-可配置 /// </summary> /// <param name="value">对象或值</param> /// <param name="jsonSetting">Json.NET配置项</param> /// <returns></returns> public static string ToJsonLower(this object value) { return JsonConvert.SerializeObject(value, JsonSettingToLower); } /// <summary> /// JSON转化为对象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="value"></param> /// <returns></returns> public static T ToObject<T>(this string value) { return JsonConvert.DeserializeObject<T>(value); } /// <summary> /// JSON转化为对象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="value"></param> /// <returns></returns> public static T ToObject<T>(this object value) { return JsonConvert.DeserializeObject<T>(value); } /// <summary> /// 属性名小写 /// </summary> public static JsonSerializerSettings JsonSettingToLower { get { return new JsonSerializerSettings { ContractResolver = new LowercaseContractResolver() }; } } } public class LowercaseContractResolver : Newtonsoft.Json.Serialization.DefaultContractResolver { protected override string ResolvePropertyName(string propertyName) { return propertyName.ToLower(); } }
还是感谢你,我写了个sql脚本把数据库字段 一次性改为 小写就行了(和json里面的保持一致,都是小写),免得动态解析再进行处理耗费性能。
declare @tablename varchar(50) declare @columnname varchar(50) declare cur_table cursor for select name from sysobjects where type='U' and name='你的表名' open cur_table fetch next from cur_table into @tablename while @@fetch_status=0 begin ----------------------------------------- declare cur_column cursor for select name from syscolumns where id=Object_Id(@tablename) open cur_column fetch next from cur_column into @columnname while @@fetch_status=0 begin declare @ch varchar(50),@ch1 varchar(50),@lowertablename varchar(50) set @ch=@tablename+'.'+@columnname set @ch1=lower(@columnname) exec sp_rename @ch,@ch1,'column' fetch next from cur_column into @columnname end close cur_column deallocate cur_column ----------------------------------------- fetch next from cur_table into @tablename end close cur_table deallocate cur_table
1.有配置项。看文档
2.大小写敏感
序列化与反序列化是有大小写敏感的。 字段不匹配是可以进行反序列化的。