使用Newtonsoft.Json序列化具有属性的对象(abc和abcSpecified--设置为false),并且abc保留在json字符串中

问题描述 投票:0回答:1

我创建了一个简单的XUnit测试以使用Newtonsoft.Json 11.0.2对此进行显示。

我已经尝试过包括Required = Required。始终,没有Seri​​alizerSettings,NullValueHandling = NullValueHandling.Ignore,等等。如果有一个名为XXX的属性,它也具有一个属性XXXSpecified(布尔),而当XXXSpecified = false时,该属性XXX不会在SerializeObject json字符串中。如果XXXSpecified = true,则显示属性XXX。我还将创建一个简单的解决方案,以测试Newtonsoft.Json的最新版本和下降版本,以了解这种情况持续了多长时间。我的最终目标是让XXX始终显示。我已经与其他几个人进行了核对,但是我希望其他人可以在这里阐明一些信息。

using System;
using Newtonsoft.Json;
using Xunit;
using Xunit.Abstractions;

namespace ABC.UnitTests
{
    public class ABCTests
    {
        #region Tests

        [Fact]
        public void AbcTest()
        {
            var abc = new Abc
            {
                DefClass = new Def
                {
                    Small = 1,
                    SmallSpecified = false,
                    Prop2 = DateTime.Now,
                    Prop2Specified = true,
                    Prop3 = DateTime.Now.AddDays(1)
                }
            };
            var json = JsonConvert.SerializeObject(abc, new JsonSerializerSettings
            {
                DateFormatHandling = DateFormatHandling.MicrosoftDateFormat,
                NullValueHandling = NullValueHandling.Ignore
            });
            Assert.True(json.Contains("\"prop1\":"));
            Assert.True(json.Contains("\"prop1Specified\":"));
            Assert.True(json.Contains("\"prop2\":"));
            Assert.True(json.Contains("\"prop2Specified\":"));
        }

        #endregion
    }

    #region Test Classes

    public class Abc
    {
        public Def DefClass { get; set; }
    }

    public class Def
    {
        [JsonProperty("prop1")]
        public int Small { get; set; }
        [JsonProperty("prop1Specified")]
        public bool SmallSpecified { get; set; }
        [JsonProperty("prop2")]
        public DateTime Prop2 { get; set; }
        [JsonProperty("prop2Specified")]
        public bool Prop2Specified { get; set; }
        [JsonProperty("prop3")]
        public DateTime Prop3 { get; set; }
    }

    #endregion    
}

谢谢,戴夫

json.net xunit.net
1个回答
0
投票

我刚与一位同事一起工作,答案是XXXSpecified属性必须为bool类型。属性XXX随即显示。

© www.soinside.com 2019 - 2024. All rights reserved.