C# 如何将缺少的json字段反序列化为null?

C# 如何将缺少的json字段反序列化为null?,c#,json,json.net,C#,Json,Json.net,我有一个JSON,看起来像这样: { "a": "foo", "b": { "c": "bar" } } { "a": "foo" } 有时,b字段不存在,如下所示: { "a": "foo", "b": { "c": "bar" } } { "a": "foo" } 下面是我将此JSON反序列化为的类: public class MyObj { private string _a;

我有一个JSON,看起来像这样:

{
    "a": "foo",
    "b": {
        "c": "bar"
    }
}
{
    "a": "foo"
}
有时,
b
字段不存在,如下所示:

{
    "a": "foo",
    "b": {
        "c": "bar"
    }
}
{
    "a": "foo"
}
下面是我将此JSON反序列化为的类:

public class MyObj
{
    private string _a;
    private MyType _b = new MyType();

    [Newtonsoft.Json.JsonProperty("a", 
    Required = Newtonsoft.Json.Required.Always)]
    public string A {
        get { return _a; }
        set { _a = value; }
    }

    [Newtonsoft.Json.JsonProperty("b",
    Required = Newtonsoft.Json.Required.DisallowNull,
    NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
    public MyType B {
        get { return _b; }
        set { _b = value; }
    }
}
在JSON中遇到缺少的
b
字段时的当前行为是,它只是用
new MyType()
对象填充该字段。当JSON中缺少
b
时,我希望将
\u b
设置为
null


但我似乎不明白。。。一定有办法做到这一点。救命啊

来自评论:只需替换
private MyType\u b=new MyType()
with
private MyType解决了这个问题


如何让人尴尬

private MyType\u b=new MyType()这是创建您的
\u b
。把它拿走。我是个白痴-谢谢