在C#中 - 如何在使用json.net进行序列化和反序列化时忽略xsd生成的postfix指定的所有属性

时间:2014-09-01 05:22:59

标签: c# json serialization xsd json.net

我有一个C#应用程序。

我有一个使用xsd.exe从xsd生成的类。该课程如下所示

public class Transaction
{
    public bool amountSpecified {get; set;}

    public double amount {get; set;}
}

以下代码显示了序列化的尝试

var transObj = new Transaction();
transObj.amount = 5.10;
var output =JsonConvert.Serialize(transObj);

输出字符串根本不包含金额字段。它包含amountSpecified false,我在序列化的json中不想要它。但是,如果我删除amountSpecified字段,它可以正常工作。

我有一大堆类,并且手动修改每个类都很痛苦。 我的问题如下 "有没有办法可以使用PostFix忽略所有字段"指定"在Json.Net?" 或者更好的是"是否可以从xsd生成c#类而不使用"指定"后缀字段?"

如果有人能指出我正确的方向,我会很高兴。 提前谢谢。

2 个答案:

答案 0 :(得分:0)

像这样添加自定义解析器类

 class CustomResolver : DefaultContractResolver
{
    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        JsonProperty prop = base.CreateProperty(member, memberSerialization);

        if (prop.PropertyName.Contains("Specified"))
        {
            prop.ShouldSerialize = obj => false;
        }

        return prop;
    }
}

然后将其与JsonSerializerSettings一起使用。以下代码是演示:

// Here is the container class we wish to serialize
        Transaction pc = new Transaction
        {
            amountSpecified=true,
            amount=23
        };

        // Serializer settings
        JsonSerializerSettings settings = new JsonSerializerSettings();
        settings.ContractResolver = new CustomResolver();
        settings.PreserveReferencesHandling = PreserveReferencesHandling.None;
        settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
        settings.Formatting = Formatting.Indented;

        // Do the serialization and output to the console
        string json = JsonConvert.SerializeObject(pc, settings);
        Console.WriteLine(json);

答案 1 :(得分:0)

除了您已找到的帖子(XSD tool appends "Specified" to certain properties/fields when generating C# code)之外,还有关于该主题的另一个链接:http://social.msdn.microsoft.com/Forums/en-US/ae260f91-2907-4f31-a554-74c8162b3b38/xsdexe-tool-creates-properties-with-specified-postfix

根据我的经验,您的解决方案是:

  • 删除所有"指定"属性(手动/通过脚本...)
  • 编写自己的序列化程序以防止创建这些属性
  • 您可以将XSD属性更改为可为空的=> xSpecified不会被创建,但属性可以为空

我想那不是你想听到的: - (