问题描述
我想 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.
有是的其中
抛出一个JsonSerializationException当缺少的成员是反序列化过程中遇到的
但我觉得这是我想要的相反。我认为,这意味着在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设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!