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