2

I have a very simply program that gets a json blob and is supposed to deserialize it to an object (users can decide the structure themselves so can't type it).

When deserializing it for some reason makes even small numbers into long.

Here is an example:

using System.Collections.Generic;
using Newtonsoft.Json;

public class Jsontest
{
    public static void testJson()
    {
        var simpleString = "[{\"name\":\"Item 1\",\"check\":1,\"num\":2}]";

        var list = new List<CustomObj>();

        list.AddRange(JsonConvert.DeserializeObject<IEnumerable<CustomObj>>(simpleString));

        return list;
    }
}

public class CustomObj
{
    [JsonProperty("name")]
    public string Name { get; set; }
    [JsonExtensionData]
    public IDictionary<string, object> PropertyValues { get; set; }
}

When hitting the return breakpoint I get this data: (Apologize for the bad visualisation, also shown In Visual Studio)

PropertyValues  Count = 2   System.Collections.Generic.IDictionary<string, object> {System.Collections.Generic.Dictionary<string, object>}
-   [0] {[check, 1]}    System.Collections.Generic.KeyValuePair<string, object>
        Key "check" string
        Value   1   object {long}
-   [1] {[num, 2]}  System.Collections.Generic.KeyValuePair<string, object>
        Key "num"   string
        Value   2   object {long}

This data is used in a different assembly where I expect it to be an int but it appears as long. Any ideas what I am doing wrong here?

Jmayn
  • 21
  • 2
  • 1
    Why did you expect an int? You didn't specify that you wan a property called `check` that contains an `int`. JSON itself doesn't specify what the numeric types are. `long` is the best option for integral values – Panagiotis Kanavos Jan 22 '20 at 15:15
  • 1
    That's what it's always done, see https://stackoverflow.com/questions/8297541/how-do-i-change-the-default-type-for-numeric-deserialization. If you want to change the type, use a custom converter, use a class to deserialize into or change your approach altogether (perhaps map the JSON object to a class of your own). – CodeCaster Jan 22 '20 at 15:16
  • I expected an int because it was a single digit number. Thanks for clarifying, the link @CodeCaster posted was really helpful! Will have to change my approach a bit. – Jmayn Jan 24 '20 at 08:27
  • As explained in the previously-linked [How do I change the default Type for Numeric deserialization?](https://stackoverflow.com/q/8297541/3744182), this is the design intent: Newtonsoft always deserializes JSON integers to `long` when doing untyped deserialization. [Overriding Default Primitive Type Handling in Json.Net](https://stackoverflow.com/q/9914333/3744182) may also help here. Close as a duplicate of those two? – dbc Jan 27 '20 at 02:01

0 Answers0