5

我正在使用 Newtonsoft JSON 使用下面的代码将 DataSet 序列化为二进制 JSON。反序列化回 DataSet 时,字段类型从 Decimal 变为 Double?有人知道出了什么问题吗?

示例代码:

static void Main(string[] args)
{
  var ds = new DataSet();
  var dt = ds.Tables.Add();
  dt.Columns.Add("Test", typeof(Decimal));
  dt.Rows.Add(new object[] { 1.23345M });

  var data = DataSetToBinJSON(ds);

  var ds2 = BinJSONToDataSet(data);
  Console.WriteLine((ds2.Tables[0].Columns[0].DataType == typeof(Decimal)) ? "Passed" : string.Format("Failed- {0}", ds2.Tables[0].Columns[0].DataType));
  Console.ReadLine();
}



/// <summary>
/// Utility function to create an optimized Binary JSON version of a DataSet
/// </summary>
public static byte[] DataSetToBinJSON(DataSet dataSet)
{
  if (dataSet == null || dataSet.Tables == null || dataSet.Tables.Count == 0)
  {
    return null;
  }

  using (var ms = new MemoryStream())
  {
    using (var writer = new BsonWriter(ms))
    {
      var serializer = new JsonSerializer();
      serializer.Serialize(writer, dataSet);
      return ms.ToArray();
    }
  }
}


/// <summary>
/// Utility function to deserialize an optimized Binary JSON serialized DataSet
/// </summary>   
public static DataSet BinJSONToDataSet(byte[] dataBytes)
{
  if (dataBytes.Length == 0)
  {
    return null;
  }

  using (var ms = new MemoryStream(dataBytes))
  {
    using (var reader = new BsonReader(ms))
    {
      var serializer = new JsonSerializer();
      return serializer.Deserialize<DataSet>(reader);
    }
  }
}
4

2 回答 2

5

修复这组的简单方法FloatParseHandling = FloatParseHandling.Decimal

示例

    public class Foo
    {
        public object Value { get; set; }
    }

    Foo original = new Foo
        {
            Value = 1.23m
        };

    string json = JsonConvert.SerializeObject(original);

    var settings = new JsonSerializerSettings
        {
            FloatParseHandling = FloatParseHandling.Decimal //hint
        };
    Foo actual = JsonConvert.DeserializeObject<Foo>(json, settings);

    // actual.Value.GetType() == 'Decimal'
于 2013-07-11T20:00:04.960 回答
0

我怀疑它与和的标准(XML)序列化DataSet有关DataTable

如果您将示例写入文件,您将看到未提供DataSet有关架构的信息。DataTable这可以在将 XML 文件读回表中时确定。

您的示例中写入文件的数据给出了以下结果:

<NewDataSet>
  <Table1>
    <Test>1.23345</Test>
  </Table1>
</NewDataSet>

DataSetwithDataTable被读取时,您无法更改列的类型(在我的测试用例中,当去往/来自 XML 时,类型是) ,string但您可以移动/转换数据:.Clone()DataTable

var clonedTable = ds.Tables[0].Clone();
clonedTable.Columns[0].DataType = typeof(decimal);
foreach (DataRow row in dt.Tables[0].Rows) {
    clonedTable.ImportRow(row);
}
于 2013-07-11T16:11:20.450 回答