15

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.

4

2 回答 2

16

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

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

通过您的示例,您将获得一个JsonSerializationException.

希望能帮助到你!

于 2013-08-09T13:21:59.793 回答
1

在类上使用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
}
于 2021-12-03T15:14:14.150 回答