Can I safely remove the fields and properties with the suffix Specified in my C# Model classes if I am only using JSON.Net

被刻印的时光 ゝ 提交于 2019-12-11 03:41:40

问题


I have a C# Application.

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;}
}

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

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].

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;

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.


回答1:


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.



来源:https://stackoverflow.com/questions/25607237/can-i-safely-remove-the-fields-and-properties-with-the-suffix-specified-in-my-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!