Json.NET MissingMemberHandling设置 [英] Json.NET MissingMemberHandling setting

查看:724
本文介绍了Json.NET MissingMemberHandling设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想 Json.NET 抛出一个 JsonSerializationException 的Json 字符串缺少了C#类需要一个属性。

I would like Json.NET to throw a JsonSerializationException when the Json string is missing a property that the C# class requires.

有是的MissingMemberHandling枚举 其中

抛出一个JsonSerializationException当缺少的成员是反序列化过程中遇到的

Throw a JsonSerializationException when a missing member is encountered during deserialization.

但我觉得这是我想要的相反。我认为,这意味着在C#类缺少的成员。我希望有一个失踪的Json成员。

but I think this is the reverse of what I want. I think this means a missing member on the c# class. I want a missing Json member.

我的代码是

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"" }";



P2是从JSON失踪。我想知道什么时候是这种情况。

P2 is missing from the json. I want to know when this is the case.

感谢。

推荐答案

您必须在P2属性设置为强制执行与 JsonPropertyAttribute

You have to set the P2 property to mandatory with the JsonPropertyAttribute

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

通过你的榜样,你会得到一个 JsonSerializationException

With your example, you will get an JsonSerializationException.

希望它帮助!

这篇关于Json.NET MissingMemberHandling设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆