【问题标题】:Json.NET MissingMemberHandling settingJson.NET MissingMemberHandling 设置
【发布时间】:2013-08-11 10:16:08
【问题描述】:

Json 字符串缺少C# 类所需的属性时,我希望Json.NET 抛出JsonSerializationException

里面有MissingMemberHandling Enumeration

当缺少成员时抛出 JsonSerializationException 在反序列化过程中遇到。

但我认为这与我想要的相反。我认为这意味着 c# 类中缺少一个成员。我想要一个缺少的 Json 成员。

我的代码是

public MyObj Deserialise(string json)
{
    var jsonSettings = new JsonSerializerSettings();
    jsonSettings.MissingMemberHandling = MissingMemberHandling.Error;

    return JsonConvert.DeserializeObject<ApiMessage>(json, jsonSettings);
}

例如

public class MyObj
{
    public string P1 { get; set; }
    public string P2 { get; set; }
}

string json = @"{ ""P1"": ""foo"" }";

json 中缺少 P2。我想知道什么时候会出现这种情况。

谢谢。

【问题讨论】:

    标签: c# json serialization json.net deserialization


    【解决方案1】:

    您必须使用JsonPropertyAttribute 将 P2 属性设置为强制

    public class ApiMessage
    {
        public string P1 { get; set; }
        [JsonProperty(Required = Required.Always)]
        public string P2 { get; set; }
    }
    

    通过您的示例,您将获得JsonSerializationException

    希望对你有帮助!

    【讨论】:

      【解决方案2】:

      在类上使用JsonObject 标记所有需要的属性:

      [JsonObject(ItemRequired = Required.Always)]
      public class MyObj
      {
          public string P1 { get; set; }  // Required.Always
          public string P2 { get; set; }  // Required.Always
      }
      

      使用JsonProperty 标记所需的各个属性:

      public class MyObj
      {
          public string P1 { get; set; }  // Required.Default
      
          [JsonProperty(Required = Required.Default)]
          public string P2 { get; set; }  // Required.Always
      }
      

      结合使用两者来做一些事情,比如标记除一个属性外的所有属性:

      [JsonObject(ItemRequired = Required.Always)]
      public class MyObj
      {
          public string P1 { get; set; }  // Required.Always
          public string P2 { get; set; }  // Required.Always
          public string P3 { get; set; }  // Required.Always
          public string P4 { get; set; }  // Required.Always
          public string P5 { get; set; }  // Required.Always
      
          [JsonProperty(Required = Required.Default)]
          public string P6 { get; set; }  // Required.Default
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-06-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多