【c#】JavaScriptSerializer 不序列化null值
首先引用dll :System.Web.Extensions。
再自定义转换器代码如下:
public class JavaScriptSerilizeConvert : JavaScriptConverter { //支持的需要转换的类型,是集合可以是多个 public override IEnumerable<Type> SupportedTypes => new List<Type>(new Type[] { typeof(Entity) }); public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) { //这样写,不管什么类型的对象都能反序列化了 var t = Activator.CreateInstance(type); var props = type.GetProperties(); if (dictionary != null) { foreach (var item in dictionary) { //这里有可能大小写不同, //兼容大小写 var p = props.Where(a => a.Name.ToLower() == item.Key.ToLower()).ToList(); if(p.Count>1) p = props.Where(a => a.Name== item.Key).ToList(); if (p.Count > 0) { int val = 0; if (p[0].PropertyType == typeof(int)) { if (int.TryParse(item.Value.ToString(), out val)) { p[0].SetValue(t, val); } }// else if double 这里要判断double 其他也一样 else { p[0].SetValue(t, item.Value); } } } return t; } return null; } public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer) { //不同的类型实体可以做不同的处理 if (obj is Entity) { Entity t = obj as Entity; var dic= new Dictionary<string, object>(); var type = t.GetType(); var props = type.GetProperties(); foreach (var item in props) { var val = item.GetValue(obj); if (val != null) { dic.Add(item.Name, val); } } return dic; } else { return new Dictionary<string, object>(); } } }
控制台测试程序:
static void Main(string[] args)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
var entity = new Entity();
entity.Id = 1;
entity.Name = null;
entity.Des = "123";
可以注册多个自定义转换器
serializer.RegisterConverters(new JavaScriptConverter[] { new JavaScriptSerilizeConvert() });
var str = serializer.Serialize(entity);
Console.WriteLine(str);
//这里需要注意 一般在不用转换器的情况下 如果实体里属性Id的类型是int类型,
//这里2出就不要加双引号,不然报错
//我这里在自定义转换器上做了处理,所以能够把string类型的2转换成int型。
var str2 = "{ \"Id\":\"2\",\"Name\":null,\"Des\":\"\"}";
var en2 = serializer.Deserialize<Entity>(str2);
Console.WriteLine(en2.Id);
Console.ReadLine();
}
实体Entity:
public class Entity
{
public int Id { get; set; }
public string Name { get; set; }
public string Des { get; set; }
}
这是简单的实体,如果有实体嵌套,也没关系,如果是都不序列化null,public override IEnumerable<Type> SupportedTypes => new List<Type>(new Type[] { typeof(Entity),typeof(SubEntity) });这里加上就行

浙公网安备 33010602011771号