如何使用Json.NET反序列化包含空值的ADO.NET DataTable?

时间:2011-05-05 18:17:58

标签: ado.net json.net

我正在尝试使用Newtonsoft.Json.Net35版本4.0.2.0来反序列化包含空值的ADO.NET DataTable。序列化工作正常:

    [Test]
    public void SerializeDataTableWithNull()
    {
        var table = new DataTable();
        table.Columns.Add("item");
        table.Columns.Add("price", typeof(double));
        table.Rows.Add("shirt", 49.99);
        table.Rows.Add("pants", 54.99);
        table.Rows.Add("shoes"); // no price

        var json = JsonConvert.SerializeObject(table);
        Assert.AreEqual(@"["
            + @"{""item"":""shirt"",""price"":49.99},"
            + @"{""item"":""pants"",""price"":54.99},"
            + @"{""item"":""shoes"",""price"":null}]", json);
    }

如果缺少值,反序列化可以正常工作:

    [Test]
    public void DerializeDataTableWithImplicitNull()
    {
        const string json = @"["
            + @"{""item"":""shirt"",""price"":49.99},"
            + @"{""item"":""pants"",""price"":54.99},"
            + @"{""item"":""shoes""}]";
        var table = JsonConvert.DeserializeObject<DataTable>(json);
        Assert.AreEqual("shirt", table.Rows[0]["item"]);
        Assert.AreEqual("pants", table.Rows[1]["item"]);
        Assert.AreEqual("shoes", table.Rows[2]["item"]);
        Assert.AreEqual(49.99, (double)table.Rows[0]["price"], 0.01);
        Assert.AreEqual(54.99, (double)table.Rows[1]["price"], 0.01);
        Assert.IsInstanceOf(typeof(System.DBNull), table.Rows[2]["price"]);
    }

但是,如果值显式为null:

    [Test]
    public void DerializeDataTableWithExplicitNull()
    {
        const string json = @"["
            + @"{""item"":""shirt"",""price"":49.99},"
            + @"{""item"":""pants"",""price"":54.99},"
            + @"{""item"":""shoes"",""price"":null}]";
        var table = JsonConvert.DeserializeObject<DataTable>(json);
        Assert.AreEqual("shirt", table.Rows[0]["item"]);
        Assert.AreEqual("pants", table.Rows[1]["item"]);
        Assert.AreEqual("shoes", table.Rows[2]["item"]);
        Assert.AreEqual(49.99, (double)table.Rows[0]["price"], 0.01);
        Assert.AreEqual(54.99, (double)table.Rows[1]["price"], 0.01);
        Assert.IsInstanceOf(typeof(System.DBNull), table.Rows[2]["price"]);
    }

DeserializeObject抛出“System.ArgumentException:无法将Column'price'设置为null。请改用DBNull。”以下解决方法适用于我的特定JSON:

        var regex = new Regex(@",?""[_\w]+"":null");
        var nullless = regex.Replace(json, string.Empty);
        var table = JsonConvert.DeserializeObject<DataTable>(nullless);

但与所有基于正则表达式的kludges一样,这显然是脆弱的。

最后,问题:

  1. 这是一个错误吗?
  2. Json.NET有很多可以挂钩的事件。有没有办法在遇到空值时通知并明确将值设置为System.DBNull?
  3. 提前致谢,

1 个答案:

答案 0 :(得分:0)

看起来这是一个可以通过替换

轻松修复的错误
dr[columnName] = reader.Value

dr[columnName] = reader.Value ?? System.DBNull.Value
Newtonsoft.Json.Converters.DataTableConverter中的

。我在跟踪器中输入了issue