使用 json 从字符串反序列化对象后.您如何知道生成的空值之间的差异

本文关键字:空值 之间 何知道 字符串 json 反序列化 对象 使用 | 更新日期: 2023-09-27 18:31:31

当 json 中的项目具有值 null 时,您如何知道差异。或者,如果该值根本不在 json 中。两者都将在实体对象中以 null 结束。(编造的)

public class Entityobject
    {
        public Document document { get; set; }
        public int randomint { get; set; }
        public string randomstr{ get; set; }
    }
Entityobject entity_obj= JsonConvert.DeserializeObject<Entityobject>(json);

因此,例如,如果 JSON 是:

String json = "{ 
randomstr = null,
randomint = 1
}"

现在文档当然也是空的。但是我怎么知道区别呢?澄清一下,我无法预先设置其他值。我实际上更喜欢一个更好的答案:只需制作另一个对象作为其他初始值然后为 null。我也仍然想在 json 中发送空值。所以我也不能发送另一个值(如"删除"左右)并在之后将其设为空。所以结束这个问题:我想知道 json 中给出的空值和发生的空值之间的区别,因为它没有包含在 json 字符串中。

希望这已经足够清楚了。提前谢谢你:)

使用 json 从字符串反序列化对象后.您如何知道生成的空值之间的差异

这不是很简单,但你可以制作你的对象,以便调用属性的 setter 将设置另一个属性字段:

class Foo
{
    private string _bar;
    public string Bar
    {
        get { return _bar; }
        set
        {
            _bar = value;
            BarSpecified = true;
        }
    }
    [JsonIgnore]
    public bool BarSpecified { get; set; }
}

如果 JSON 中存在 Bar,则BarSpecified为真,否则为假。

请注意,名称BarSpecified不是随机选择的;后缀Specified对 JSON.NET(以及XmlSerializer)具有特殊含义:它控制属性是否序列化。

因此,如果反序列化对象并再次序列化它,则新的 JSON 将与原始 JSON 相同(就属性是否存在于 JSON 而言)。

您可以

EntityObject中的每个字段设置默认值。这样,您可以确保如果值确实等于null则显式分配null

例如 (C# 5):

public class Entityobject
{
    private Document _document = Document.EmptyDocument;
    public Document document
    {
        get
        {
            return _document;
        }
        set
        {
            _document = value;
        }
    }
    private int? _randomint = 0;
    public int? randomint
    {
        get
        {
            return _randomint;
        }
        set
        {
            _randomint = value;
        }
    }
    private string _randomstr = String.Empty;
    public string randomstr
    {
        get
        {
            return _randomstr;
        }
        set
        {
            _randomstr = value;
        }
    }
}

在 C# 6 中甚至更容易:

public class Entityobject
{
    public Document document { get; set; } = Document.EmptyDocument;
    public int randomint { get; set; } = 0;
    public string randomstr{ get; set; } = String.Empty;
}