我正在使用JavaScriptSerializer来序列化一些实体对象。
问题是,许多公共属性包含null或默认值。有没有办法让JavaScriptSerializer排除具有null或默认值的属性?
我希望生成的JSON不那么详细。
答案 0 :(得分:31)
仅供参考,如果您想使用更简单的解决方案,以下是我使用JavaScriptSvertizer的JavaScriptConverter实现实现此目的:
private class NullPropertiesConverter : JavaScriptConverter
{
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
throw new NotImplementedException();
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
var jsonExample = new Dictionary<string, object>();
foreach (var prop in obj.GetType().GetProperties())
{
//check if decorated with ScriptIgnore attribute
bool ignoreProp = prop.IsDefined(typeof(ScriptIgnoreAttribute), true);
var value = prop.GetValue(obj, BindingFlags.Public, null, null, null);
if (value != null && !ignoreProp)
jsonExample.Add(prop.Name, value);
}
return jsonExample;
}
public override IEnumerable<Type> SupportedTypes
{
get { return GetType().Assembly.GetTypes(); }
}
}
然后使用它:
var serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new JavaScriptConverter[] { new NullPropertiesConverter() });
return serializer.Serialize(someObjectToSerialize);
答案 1 :(得分:12)
对我有用的解决方案:
序列化的类和属性将按如下方式进行修饰:
[DataContract]
public class MyDataClass
{
[DataMember(Name = "LabelInJson", IsRequired = false)]
public string MyProperty { get; set; }
}
IsRequired是关键项目。
实际的序列化可以使用DataContractJsonSerializer完成:
public static string Serialize<T>(T obj)
{
string returnVal = "";
try
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, obj);
returnVal = Encoding.Default.GetString(ms.ToArray());
}
}
catch (Exception /*exception*/)
{
returnVal = "";
//log error
}
return returnVal;
}
答案 2 :(得分:5)
Json.NET具有自动排除空值或默认值的选项。
答案 3 :(得分:4)
您可以实施JavaScriptConverter
并使用JavaScriptSerializer
的{{3}}方法进行注册。
答案 4 :(得分:1)
此代码为null null,数值类型的默认值为(0)
private class NullPropertiesConverter : JavaScriptConverter
{
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
throw new NotImplementedException();
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
var jsonExample = new Dictionary<string, object>();
foreach (var prop in obj.GetType().GetProperties())
{
//this object is nullable
var nullableobj = prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>);
//check if decorated with ScriptIgnore attribute
bool ignoreProp = prop.IsDefined(typeof(ScriptIgnoreAttribute), true);
var value = prop.GetValue(obj, System.Reflection.BindingFlags.Public, null, null, null);
int i;
//Object is not nullable and value=0 , it is a default value for numeric types
if (!(nullableobj == false && value != null && (int.TryParse(value.ToString(), out i) ? i : 1) == 0) && value != null && !ignoreProp)
jsonExample.Add(prop.Name, value);
}
return jsonExample;
}
public override IEnumerable<Type> SupportedTypes
{
get { return GetType().Assembly.GetTypes(); }
}
}
答案 5 :(得分:0)
不改变脚趾DataContractSerializer
您可以使用ScriptIgnoreAttribute
[1] http://msdn.microsoft.com/en-us/library/system.web.script.serialization.scriptignoreattribute.aspx
答案 6 :(得分:0)
为了让那些在谷歌上找到这个的人受益,请注意在使用Newtonsoft.Json序列化期间可以原生跳过空值
var json = JsonConvert.SerializeObject(
objectToSerialize,
new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore});