【发布时间】:2012-11-20 22:14:35
【问题描述】:
在 Windows 上的 Visual Studio 中尝试了代码以确定。
Mono 框架似乎不支持 DataMemberAttribute 的 EmitDefaultValue 参数。使用以下代码:
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,但不应输出,因为它是 string 类型的默认值。
Windows 上 VS 的正确输出是:
{"out_value":"This is a what?","set_on_serialize":"A brick!"}
这是 Mono 中的错误还是我遗漏了什么?
【问题讨论】:
-
在mono-project.com/Bugs上报告这个错误
-
另外,请在您的问题中包含版本号,尤其是在指出可能存在的错误时。
标签: c# json serialization mono portability