我可以安全地删除字段和属性与指定的在我的C#模型类,如果我只使用后缀JSON.Net我的、我只、后缀、字段

2023-09-05 03:22:13 作者:神爱众人我只爱你

我有一个C#应用程序。

I have a C# Application.

我有一个从XSD生成的类。这个类看起来如下

I have a class that is generated from an xsd. The class looks as below

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

    public double amount {get; set;}
}

如果你在类注意到以上,随着属性量,发生器还产生一个称为amountSpecified属性。

If you notice in the class above, along with the property amount, the generator has also generated a property called amountSpecified.

我知道,指定所需的所有非可空字段/属性的属性后缀,因为这是XML序列化的要求,如本[文章] [1]。

I know that the properties with suffix "Specified" are required for all non-nullable field/property, because this is the requirement of XML Serializer as mentioned in this [article][1].

不过,我只用JSON序列化和反序列化(与JSON.NET),我还需要与指定后缀的那些领域?如果删除它们,我应该让我的字段/属性可为空,如下图所示?

However I only use JSON serialization and deserialization(with JSON.NET), do I still need those fields with "Specified" suffix? If I remove them should I make my fields/properties nullable as shown below?

double? amount;

我的问题存在是所有这一切由JSON.Net内部处理的?我可以安全地删除所有字段后缀指定的,而不是让我的领域可为空?

My question being is all of this internally handled by JSON.Net? Can I safely remove all the fields with suffix "specified" and not make my fields nullable?

我会很高兴,如果有人能在正确的方向指向我。 在此先感谢。

I would be very glad if someone can point me in the right direction. Thanks in Advance.

推荐答案

随着自2008年讨论< /一>,他们用它来支持可空类型。此外,我试着用这个code

As discussed since 2008, they fixed it to support nullable type. Also I tried with this code

using System;
using Newtonsoft.Json;

namespace TestJson
{
    class Test {
        public double? amount { get; set; }
    }

    class MainClass
    {
        public static void Main(string[] args)
        {
            string jsonStr = JsonConvert.SerializeObject(new Test());
            string jsonStr2 = JsonConvert.SerializeObject(new Test { amount = 5 } );
            Console.WriteLine(jsonStr);
            Console.WriteLine(jsonStr2);
            Console.ReadLine();
        }
    }
}

它工作得很好:

It works just fine:

{"amount":null}
{"amount":5.0}

和属性与指定后缀不是必需的。

And the properties with Specified suffix are not required.