• json null


    {
    "ResourceId": 0,
    "JsonKey": "Account",
    "GroupId": 21,
    "Locale": "en-US",
    "JsonValue": {
    "Columns": {
    "2": "2",
    "Title": "343434"
    },
    "Labels": {},
    "Others": {},
    "Tips": {}
    }
    }

    第一种:使用对象的字段属性设置JsonProperty来实现(不推荐,因为需要手动的修改每个字段的属性)

    1
    2
    3
    4
    5
    6
    7
    public class UserInfo
    {
      [JsonProperty("id")]
      public int Id{ set; get; }
      [JsonProperty("userName")]
      public string UserName{ set; get; }
    }

     第二种:使用newtonsoft.json来设置格式化的方式(推荐使用)

    1
    2
    3
    4
    5
    6
    7
    var user = new { Name = "john", Age = 19 };
     var serializerSettings = new JsonSerializerSettings
          {
            // 设置为驼峰命名
            ContractResolver = new CamelCasePropertyNamesContractResolver()
          };
    var userStr = JsonConvert.SerializeObject(user, Formatting.None, serializerSettings);
    26down voteaccepted

    This should work:

    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);
        }
    }
  • 相关阅读:
    GitHub 如何创建 Access Token
    Fact Table 数据表什么意思
    高基数数据特性是什么意思
    Edge 浏览器的隐藏 URL QR 生成器
    Apache Druid 安装的时候进行 Java 版本校验没有输出
    Apache Druid 简介
    如何在 Discourse 中批量移动主题到不同的分类中
    素材
    Drawable转bitmap
    Drawable与 Bitmap 转换总结
  • 原文地址:https://www.cnblogs.com/zwei1121/p/9644964.html
Copyright © 2020-2023  润新知