Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 473
Sam Leach Avatar asked Aug 09 '13 13:08

Sam Leach


2 Answers

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!

like image 144
Joffrey Kern Avatar answered Sep 21 '22 20:09

Joffrey Kern


Use JsonObject on the class to mark all properties required:

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

Use JsonProperty to mark individual properties required:

public class MyObj
{
    public string P1 { get; set; }  // Required.Default

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

Use both in combination to do things like mark all but one property required:

[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
}
like image 35
MarredCheese Avatar answered Sep 20 '22 20:09

MarredCheese