using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks; namespace Json.Useage
{
/// <summary>
/// serialize null to empty
/// </summary>
class Program
{
static void Main(string[] args)
{
var test = new Test();
var settings = new JsonSerializerSettings() { ContractResolver = new NullToEmptyStringResolver() };
var obj = JsonConvert.SerializeObject(test, settings);
var obj2 = JsonConvert.SerializeObject(test); var json = "{'Field': null }";
var t = JsonConvert.DeserializeObject<Test>(json, settings);
Console.WriteLine(t.Field);
Console.WriteLine(obj2);
Console.WriteLine(obj); Console.ReadKey();
}
} public class Test
{
[DefaultValue("")]
public string Field { get; set; }
} public class NullToEmptyStringResolver : Newtonsoft.Json.Serialization.DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
return type.GetProperties()
.Select(p =>
{
var jp = base.CreateProperty(p, memberSerialization);
jp.ValueProvider = new NullToEmptyStringValueProvider(p);
return jp;
}).ToList();
}
} public class NullToEmptyStringValueProvider : IValueProvider
{
PropertyInfo _MemberInfo;
public NullToEmptyStringValueProvider(PropertyInfo memberInfo)
{
_MemberInfo = memberInfo;
} public object GetValue(object target)
{
object result = _MemberInfo.GetValue(target); if (_MemberInfo.PropertyType == typeof(string) && result == null) result = " "; return result; } public void SetValue(object target, object value)
{
if (_MemberInfo.PropertyType == typeof(string) && value == null) value = ""; _MemberInfo.SetValue(target, value);
}
} }

这里只写了 string 类型的,其他类型需要转换的再加 if 条件就好了

05-11 20:25