.net Core 3.1 Newtonsoft.Json converts dictionary<int,string> key to string

Viewed 701

My custom object's one of properties is dictionary and I need to convert whole object to json string but JsonConvert changes dictionary key from Int to String which is what I don't want to happen.

var test = new Dictionary<int, string>
{
    [1] = "2"
};

var jsonDictionary = JsonConvert.SerializeObject(test, Formatting.None);

// output {"1":"2"}

My desired output should be { 1 : "2" }

1 Answers

I'm hoping this might clear things up a little and hope it helps! When we call Json.SerializeObject we're saying "take my object and turn it into a string representation so that I can (for example) transmit my object over HTTP".

But when you deserialize the string representation, everything goes back to the original types. It's not so much that you can "avoid conversion" but what happens is Json does the conversion automatically so we don't have to.

One thing you might consider trying, that will give you very fine control over this process, is to make a custom class like so:

class CustomDictionary : Dictionary<int, string> { }

Then the "round trip" serialize/deserialize puts you back to an object where the Key is truly an int and only the Value is a string:

    static void Main(string[] args)
    {
        CustomDictionary myDict = new CustomDictionary();
        myDict[1] = "Two";
        string stringRepresentation = JsonConvert.SerializeObject(myDict);
        Console.WriteLine(stringRepresentation); // looks like {"1":"Two"}

        // Now it's back to normal Dictionary<int, string>
        CustomDictionary deserializedDict = JsonConvert.DeserializeObject<CustomDictionary>(stringRepresentation);
    }
Related