我正在使用JavaScriptSerializer来序列化一些实体对象。
问题在于,许多公共属性包含空值或默认值。是否有任何方法可以使JavaScriptSerializer排除具有空或默认值的属性?
我希望生成的JSON更加简洁。
我正在使用JavaScriptSerializer来序列化一些实体对象。
问题在于,许多公共属性包含空值或默认值。是否有任何方法可以使JavaScriptSerializer排除具有空或默认值的属性?
我希望生成的JSON更加简洁。
顺便说一下,如果您想选择更简单的解决方案,这是我使用 JavaScriptConverter 实现和 JavaScriptSerializer 完成此操作的方法:
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);
[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;
}
var json = JsonConvert.SerializeObject(
objectToSerialize,
new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore});
Json.NET有选项可以自动排除空值或默认值。
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();
}
}
}
不改变DataContractSerializer的情况下
您可以使用ScriptIgnoreAttribute
[1] http://msdn.microsoft.com/en-us/library/system.web.script.serialization.scriptignoreattribute.aspx