我有一个类似下面的类
[Serializable]
public class sample
{
private int m_width;
private int m_height;
public int Width
{
get
{
return this.m_width;
}
set
{
this.m_width = value;
}
}
public int Height
{
get
{
return this.m_height;
}
set
{
this.m_height = value;
}
}
}
如果我使用 DataContractJsonSerializer
序列化这个类的对象,我会得到如下的 json
字符串:
{"m_height":1345,"m_width":1234}
如果我使用 Newtonsoft.Json.dll 对其进行序列化,我将得到如下所示的输出:
{"Width":1234,"Height":1345}
如果类标记为可序列化,为什么 DataContractSerializer 使用支持字段进行序列化?
有什么方法可以使用 Newtonsoft.Json.dll
最佳答案
我们有一些标记为 [Serializable]
的对象,因此可以使用传统方法对它们进行序列化,但我们需要将其干净地序列化为 JSON 以便与 Web API 一起使用。将 IgnoreSerializableAttribute
设置为 true
将阻止 Newtonsoft.Json 的行为类似于 Microsoft 的序列化程序,而只会序列化公共(public)属性。
TLDR:将此添加到 WebApiConfig.cs:
((Newtonsoft.Json.Serialization.DefaultContractResolver)config.Formatters.JsonFormatter.SerializerSettings.ContractResolver).IgnoreSerializableAttribute = true;
关于c# - 当我们使用 JSON.Net 序列化可序列化对象时,JSON 字符串与 DatacontractJSON 序列化器不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18314929/