And*_*rus 0 c# asp.net-mvc serialization json json.net
实体对象需要转换为字符串以将它们存储在日志文件中以供人类阅读。属性可以在运行时添加到派生实体。序列化在实体基类中定义。我尝试了下面的代码,但它也返回具有空值的属性。由于许多属性具有空值,这使得日志难以阅读。
Hoq 仅序列化非空属性?我也试过
var jsonSettings = new JsonSerializerSettings()
{
DefaultValueHandling = DefaultValueHandling.Ignore,
Formatting = Formatting.Indented,
TypeNameHandling= TypeNameHandling.All
};
return JsonConvert.SerializeObject(this, GetType(), jsonSettings);
Run Code Online (Sandbox Code Playgroud)
这仅序列化newtonsoft json 中确认的 EntityBase 类属性不会序列化派生类属性
public class EntityBase {
public string Serialize()
{
var s = new System.Web.Script.Serialization.JavaScriptSerializer();
s.Serialize(this);
}
}
public class Customer: EntityBase {
public string Name, Address;
}
Run Code Online (Sandbox Code Playgroud)
测试用例:
var cust= new Customer() { Name="Test"};
Debug.Writeline( cust.Serialize());
Run Code Online (Sandbox Code Playgroud)
观察到:结果包含“地址”:空
预期:结果不应包含地址属性。
使用 ASP.NET/Mono MVC4、.NET 4.6
您可以创建自己的序列化程序来忽略空属性。
JsonConvert.SerializeObject(
object,
Newtonsoft.Json.Formatting.None,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3239 次 |
最近记录: |