Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Newtonsoft JSON- Conversion to/from DataSet causes Decimal to become Double?

Tags:

c#

.net

json.net

I'm using Newtonsoft JSON to serialize a DataSet to binary JSON using the code below. When de-serializing back to a DataSet, the field type changes from a Decimal to a Double? Does anybody know what's going wrong?

Sample code:

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);
    }
  }
}
like image 556
Keith Blows Avatar asked Jul 11 '13 15:07

Keith Blows


People also ask

Is Newtonsoft JSON obsolete?

The Newtonsoft. Json. Schema namespace provides classes that are used to implement JSON schema. Obsolete.

What does Jsonconvert Deserializeobject do?

Deserializes the JSON to the specified . NET type. Deserializes the JSON to the specified . NET type using a collection of JsonConverter.

Which is better Newtonsoft JSON or System text JSON?

Text. Json is much faster than the Newtonsoft. Json.

What is Jsonserializersettings?

Specifies the settings on a JsonSerializer object.


1 Answers

Easy way to fix this set FloatParseHandling = FloatParseHandling.Decimal

Example:

    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'
like image 89
oakio Avatar answered Oct 19 '22 22:10

oakio