Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
950 views
in Technique[技术] by (71.8m points)

c# - Json.NET MissingMemberHandling setting

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

There is the MissingMemberHandling Enumeration which

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

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.

My code is

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

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

For example

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

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

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

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

With your example, you will get an JsonSerializationException.

Hope it helps!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...