2017-04-19 62 views
2

我创建了一个简单的类:C#JsonConvert转换无效的对象

public class TestObject 
{ 
    public TestObject(int id, string name, List<string> list) 
    { 
     this.Id = id; 

     if (name == null) 
     { 
      throw new ArgumentException(); 
     } 
     this.Name = name; 
     this.List = list; 
    } 

    [Required] 
    public int Id { get; } 

    public string Name { get; } 

    public List<string> List { get; } 
} 

,我想反序列化和验证,如果原单JSON是正确的:

[Test] 
public void MissingIdArgument() 
{ 
    var str = @"{ ""name"": ""aa"" } "; 
    Assert.Throws<JsonSerializationException>(() => 
     JsonConvert.DeserializeObject<TestObject>(
      str, 
      new JsonSerializerSettings() 
      { 
       CheckAdditionalContent = true, 
       DefaultValueHandling = DefaultValueHandling.Include, 
       MissingMemberHandling = MissingMemberHandling.Error, 
       NullValueHandling = NullValueHandling.Include, 

      })); 
} 

我会epxect这个测试通过但是它没有。它不检查在原始JSON中是否存在IdList字段(尽管Id字段是必需的)。向JSON添加一些随机属性会导致实际抛出异常。

如何使JsonConvert在某种意义上是严格的,即测试(因为它)会通过?

确切的说我会希望:

  • { id: 1, name: "aa" } - 失败(因为没有列表定义)
  • { name: "aa", list: null } - 失败(因为没有ID被定义)
  • { id: 0, name: "", list: null } - 通过
+1

如何使用[json schema](http://www.newtonsoft.com/jsonschema)设置关于您的json的规则? –

回答

2

我想说,你是以错误的方式指定所需的属性。

您应该使用JsonProperty attributeRequired property而不是Required属性。

例如:

public class TestObject 
{ 
    // Id has to be present in the JSON 
    [JsonProperty(Required = Required.Always)] 
    public int Id { get; } 

    // Name is optinional 
    [JsonProperty] 
    public string Name { get; } 

    // List has to be present in the JSON but may be null 
    [JsonProperty(Required = Required.AllowNull)] 
    public List<string> List { get; } 
} 

Required属性可以从Newtonsoft.Json.Required enum被设定为一个常数。

检查JsonPropertyAttribute class documentation的其他配置可能性。

您还可以在官方文档中检查example

+0

虽然Phill的解决方案可能也会起作用,但这不需要对解析器进行任何更改。谢谢 –