c# - Json 转换空字符串而不是 null

标签 c# json null string

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

[JsonProperty(PropertyName = "myProperty", DefaultValueHandling = DefaultValueHandling.Populate)]
[DefaultValue("")]
public string MyProperty{ get; set; }

我在 Json 字符串中的结果:

"myProperty": null,

我想要什么

"myProperty": "",

我也尝试创建一个没有任何效果的转换器,can 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 How to deserialize null as empty string?

最佳答案

这应该可行:

var settings = new JsonSerializerSettings() { ContractResolver= new NullToEmptyStringResolver() };
var str = JsonConvert.SerializeObject(yourObj, settings);

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Reflection;

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);
    }
}

关于c# - Json 转换空字符串而不是 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23830206/

相关文章:

php - 是否有更好的解决方案来检查许多变量以查看其中一个变量在 PHP 中是否为空?

java - java.lang.Object#getClass() 的 Eclipse 外部空注释

c# - 从 XML 中检索属性

c# - 有没有办法将 TransactionScope 与现有连接一起使用?

javascript - Angular 收集数据最佳实践

ios - 有错误的 RACSignal 映射

javascript - 从 HTML div 结构创建多维 JSON 结构

c# - 参数为空时如何解决歧义?

c# - 使用 Async 延迟加载属性

c# - 对地理形状进行分组