Json转换空字符串而不是null

我正在尝试序列化我的结构,以便未获得值的字符串获得其默认值“”而不是null

[JsonProperty(PropertyName = "myProperty", DefaultValueHandling = DefaultValueHandling.Populate)]

[DefaultValue("")]

public string MyProperty{ get; set; }

我在Json字符串中的结果:

"myProperty": null,

我想要的是

"myProperty": "",

我也尝试创建一个没有任何影响的转换器,由于某些原因,甚至不能触发Convert和WriteJson函数:

[JsonProperty(PropertyName = "myProperty")]

[JsonConverter(typeof(NullToEmptyStringConverter))]

public string MyProperty{ get; set; }

class NullToEmptyStringConverter : JsonConverter

{

public override bool CanConvert(Type objectType)

{

return objectType == typeof(object[]);

}

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)

{

throw new NotImplementedException();

}

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)

{

if (value == null)

writer.WriteValue("");

}

}

这没有帮助Json.Net如何将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);

}

}

以上是 Json转换空字符串而不是null 的全部内容, 来源链接: utcz.com/qa/430857.html

回到顶部