确定在 Windows 上的 Visual Studio 中尝试了代码。
Mono 框架似乎不EmitDefaultValue
尊重DataMemberAttribute
. 使用以下代码:
using System;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
namespace MyApp
{
class MainClass
{
public static void Main (string[] args)
{
Cereal specialK = new Cereal();
specialK.TheValue="This is a what?";
var ser = new DataContractJsonSerializer(typeof(Cereal));
MemoryStream stm = new MemoryStream();
ser.WriteObject(stm, specialK);
string json = System.Text.Encoding.UTF8.GetString(stm.ToArray());
Console.WriteLine(json);
Console.ReadLine();
}
}
[DataContract]
class Cereal
{
[DataMember(Name="set_on_serialize")]
private string _setOnSerialize = string.Empty;
[DataMember(Name = "default_export", EmitDefaultValue = false)]
private string _default_null;
public Cereal() { }
[DataMember(Name = "out_value")]
public string TheValue
{
get;
set;
}
[OnSerializing]
void OnSerializing(StreamingContext content)
{
this._setOnSerialize = "A brick!";
}
}
}
Mono 中的输出结果为:
{"default_export":null,"out_value":"This is a what?","set_on_serialize":""}
default_export 属性被导出为 null 但不应输出,因为它是 type 的默认值string
。
Windows 上 VS 的正确输出是:
{"out_value":"This is a what?","set_on_serialize":"A brick!"}
这是 Mono 中的错误还是我遗漏了什么?