Newtonsoft.Json 中 json数据中的 null如何转换成 ""?个人只看到一个忽略空值的属性JsonSerializerSettings jsetting=new JsonSerializerSettings();
jsetting.NullValueHandling = NullValueHandling.Ignore;json:{ Name = "Jack", Age = 31, Gender = "Male", DepartmentName = "Personnel Department", Leader = null }
转换的结果:{ Name = "Jack", Age = 31, Gender = "Male", DepartmentName = "Personnel Department", Leader = ""}
如何使json串中的 null能转成 "" ,求解!
2 回答
慕容3067478
TA贡献1773条经验 获得超3个赞
需要自己写一个NullToEmptyStringResolver,下面的代码来自Json Convert empty string instead of null:
var settings = new JsonSerializerSettings() { ContractResolver= new NullToEmptyStringResolver() };var str = JsonConvert.SerializeObject(yourObj, settings);
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) { _MemberInfo.SetValue(target, value); } }
- 2 回答
- 0 关注
- 3411 浏览
添加回答
举报
0/150
提交
取消