5

If I deserialize some JSON to a dictionary of objects like so:

var properties = "{\"property1\":\"\",\"property2\":2}";

var dictionary = JsonConvert.DeserializeObject<Dictionary<string, object>>(properties);

Console.WriteLine(dictionary["property2"].GetType()); // Prints System.Int64

The integer-valued property property2 is getting automatically deserialized as a long and not an int.

Can I convert automatically to int?

dbc
  • 104,963
  • 20
  • 228
  • 340
john john
  • 51
  • 2
  • 2
    This is, apparently, the intended functionality. When you deserialize to `object`, Json.NET will chose an appropriate concrete data type; for integer values it chooses `long` unconditionally. If you don't like that, see e.g. [How do I change the default Type for Numeric deserialization?](https://stackoverflow.com/q/8297541/3744182) or [Overriding Default Primitive Type Handling in Json.Net](https://stackoverflow.com/q/9914333/3744182). In fact this may be a duplicate of those two, agree? – dbc Jan 17 '20 at 19:19
  • `var properties = "{\"property1\":\"\",\"property2\":2}"; var t = JsonConvert.DeserializeObject>(properties); Console.WriteLine(string.Join(" ", t.ToList().Select(kvp => kvp.Value?.GetType())));` run that... – Trevor Jan 17 '20 at 19:19

0 Answers0