简体   繁体   中英

C# Newtonsoft json serialization Dictionary<int, int> get saved as <string, int>

I'm trying to load some saved json string and turn it into a <int, int> dictionary, then add some items and then turn it back into a string. But for some reason the key gets saved as a string, not int.

I'm using the following code:

using Newtonsoft.Json;

var dictionary = JsonConvert.DeserializeObject<Dictionary<int, int>>("{}");
dictionary[1] = 1;
string updatedDictionary = JsonConvert.SerializeObject(dictionary);
Debug.Log(updatedDictionary); // {"1":1}
Debug.Log(updatedDictionary[1]); // "

but the updatedDictionary is printed as {"1":1} ... why is that? And how can I fix this? I cannot event just convert to string when looking up the dictionary because it only allows int look ups. So I really need to make sure that the json is saved as int int key value pair, and not turn into string keys.

The same happens when I do dictionary.Add(1, 1) So I'm pretty sure the problem lies in the SerializeObject call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM