Newtonsoft.Json 中 json數(shù)據(jù)中的 null如何轉(zhuǎn)換成 ""?個(gè)人只看到一個(gè)忽略空值的屬性JsonSerializerSettings jsetting=new JsonSerializerSettings();
jsetting.NullValueHandling = NullValueHandling.Ignore;json:{ Name = "Jack", Age = 31, Gender = "Male", DepartmentName = "Personnel Department", Leader = null }
轉(zhuǎn)換的結(jié)果:{ Name = "Jack", Age = 31, Gender = "Male", DepartmentName = "Personnel Department", Leader = ""}
如何使json串中的 null能轉(zhuǎn)成 "" ,求解!
2 回答

慕容3067478
TA貢獻(xiàn)1773條經(jīng)驗(yàn) 獲得超3個(gè)贊
需要自己寫一個(gè)NullToEmptyStringResolver,下面的代碼來(lái)自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); } }

臨摹微笑
TA貢獻(xiàn)1982條經(jīng)驗(yàn) 獲得超2個(gè)贊
直接字符串替換不就好了么 null 替換成“”
http://www.cnblogs.com/yanweidie/p/4605212.html
- 2 回答
- 0 關(guān)注
- 3526 瀏覽
添加回答
舉報(bào)
0/150
提交
取消