由网友(向阳花)分享简介:我使用JavaScriptSerializer序列化一些实体对象。I'm using JavaScriptSerializer to serialize some entity objects.现在的问题是,许多的公共属性包含空值或默认值。有没有什么办法让JavaScriptSerializer与空或默认值排除属性...
我使用JavaScriptSerializer序列化一些实体对象。
I'm using JavaScriptSerializer to serialize some entity objects.
现在的问题是,许多的公共属性包含空值或默认值。有没有什么办法让JavaScriptSerializer与空或默认值排除属性?
The problem is, many of the public properties contain null or default values. Is there any way to make JavaScriptSerializer exclude properties with null or default values?
我想生成的JSON是更简洁。
I would like the resulting JSON to be less verbose.
推荐答案
这是为我工作的解决方案:
The solution that worked for me:
序列化的类和属性将被装饰成如下:
The serialized class and properties would be decorated as follows:
[DataContract]
public class MyDataClass
{
[DataMember(Name = "LabelInJson", IsRequired = false)]
public string MyProperty { get; set; }
}
IsRequired是关键项目。
IsRequired was the key item.
可以使用DataContractJsonSerializer做实际的序列化:
The actual serialization could be done using 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;
}
相关推荐
最新文章