Reputation: 47
I'm trying to take a Json data set in Unity-C# and turn it into a Dictionary
{
1:
{
"uni_number": 001,
"level" : 3,
"Hp" : 15
},
2:
{
"uni_number": 000,
"level" : 0,
"Hp" : 0
}
}
(I can have the intigers strings if needed) I also need to turn the dictionary file back into a json file when I want to save the game.
I've checked a couple of different StackOverflow questions and I can't seem to figure it out. I've tried using JsonUtility to parse it into a Dictionary.
Here's the json file I want to turn into a dictionary
string json = @"1:{""uni_number"": 001,""level"" : 3,""Hp"" : 15},2:{""uni_number"": 000,""level"" : 0,""Hp"" : 0}";
This is one of the things that I tried if I can get it to work than I should be able to finish it from there after I add another depth to it.
string json = @"{""uni_number"": ""001"",""level"" : ""3"", ""Hp"": ""15""}";
Dictionary<string, string> loadedData = JsonUtility.FromJson<Dictionary<string, string>>(json);
This doesn't give me an error, but when I try to print it, it prints nothing. Here's how I print it.
foreach (KeyValuePair<string, string> kvp in loadedData)
{
print("Key = {0}, Value = {1}");
print(kvp.Key);
print(kvp.Value);
}
I've also tried
string loadedData = JsonUtility.FromJson<string>(@"{""uni_number"": ""001"",""level"" : ""3"", ""Hp"": ""15""}");
print (loadedData)
and it doesn't print anything, so I think I'm using the JsonUtility function wrong, but I don't know how.
If I can't get it to work I could probably make my own function that turns json files into dictionarys, but it's probably going to be a big pain in the but.
Upvotes: 2
Views: 10796
Reputation: 1335
I am using Newtonsoft.Json and it works : (notice that each value is a dictionary (key,value pairs) aswell)
string json = @"{
1:
{
""uni_number"": 001,
""level"" : 3,
""Hp"" : 15
},
2:
{
""uni_number"": 000,
""level"" : 0,
""Hp"" : 0
}
}";
var values = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string,string>>>(json);
foreach (var uni in values)
{
//you can print values here or add to a list or ...
string uni_number= uni.Value["uni_number"];
string level= uni.Value["level"];
string Hp= uni.Value["Hp"];
}
Upvotes: 7