C#JsonConvert转换无效对象

时间:2017-04-19 12:37:30

标签: c# json json.net

我创建了一个简单的类:

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,

            }));
}

我会让这个测试通过,但事实并非如此。它不会检查原始JSON中是否存在IdList字段(尽管需要Id字段)。向JSON添加一些随机属性会导致实际抛出异常。

如何使JsonConvert严格认为此测试(原样)会通过?

确切地说,我希望:

  • { id: 1, name: "aa" } - 失败(因为没有定义列表)
  • { name: "aa", list: null } - 失败(因为没有定义id)
  • { id: 0, name: "", list: null } - 传递

1 个答案:

答案 0 :(得分: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