【问题标题】:Set requried field while Deserializing using Json.Net使用 Json.Net 反序列化时设置所需字段
【发布时间】:2014-05-15 15:49:21
【问题描述】:

我有一个类 Foo 如下

public class Foo
{
   public ClassA A {get;set;}
   public string B {get;set;}
}
public class ClassA
{
   public string C {get;set;}
}

当我得到一个 Json 字符串(比如 fooJson)时,我想将它反序列化为具有以下条件的 Foo 对象

  1. 对象必须具有属性 Foo.A
  2. Foo.B 是可选的
  3. Foo.A.C 是可选的

我尝试使用 MissingMemberHandling = MissingMemberHandling.Error 作为我的 JsonSerializerSettings 的一部分。但即使 Foo.B 丢失也会引发错误。

【问题讨论】:

    标签: c# json json.net deserialization json-deserialization


    【解决方案1】:

    如果您希望某些属性是可选的,而某些属性是必需的,实现此目的的最简单方法是使用 [JsonProperty] 属性标记您的类,指示哪些属性是必需的,例如:

    public class Foo
    {
        [JsonProperty(Required = Required.Always)]
        public ClassA A { get; set; }
        public string B { get; set; }
    }
    public class ClassA
    {
        public string C { get; set; }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多