c# - Newtonsoft JSON- 与 DataSet 之间的转换会导致 Decimal 变为 Double?

标签 c# .net json.net

我正在使用 Newtonsoft JSON 通过以下代码将数据集序列化为二进制 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);
    }
  }
}

最佳答案

修复此集合的简单方法 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'

关于c# - Newtonsoft JSON- 与 DataSet 之间的转换会导致 Decimal 变为 Double?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17597594/

相关文章:

c# - 使用 Unity 2 和 MVC 3 将类注入(inject)身份验证属性

c# - 您可以从 iOS C 插件 "on the spot"写入 Unity 纹理吗?

c# - 如何将参数传递给 Entity Framework 中的 DbSet.SqlQuery 方法

c# - CollectionViewSource.GetDefaultView 在 SetBinding 之后返回 null

c# - C# 中的 JSON 到 XML 转换

asp.net-mvc - 在 MVC4 项目中使用 Json.NET 序列化器

c# - 使用已知和未知字段反序列化 json

c# - 启动时运行后台任务

.net - 反射 GetExecutingAssembly 正在抛出 StackOverflow

c# - 将 child 添加到现有的树节点