Hello,
I have this situation:
public TMP_Dropdown dropdown;//assigned on Editor, cleared on start
__
{
{ "Desc1", "234" },
{ "Desc2", "30" },
{ "Desc3", "50" }
};
dropdown.AddOptions(myDic.Keys.ToList());//this works, puts "Desc..." on dropdown options
dropdown.onValueChanged.AddListener(DropdownValueChanged);//this works too, call DropdownValueChanged```
__
void DropdownValueChanged(int newPosition)
{
string realValue = myDic.Values.ElementAt(newPosition);
Debug.Log(realValue);
//this works too, prints 234 to Desc1, 30 to Desc2, 50 to Desc3
}```
__
Now, the problem:
I am downloading a JSON in that format (can not change…):
{"Id":183,"description":"blahblahblah"},
{"Id":184,"description":"blehblehbleh"},
{"Id":1000,"description":"and so on..."}
]```
How can I convert it to became a dictionary like
```{
{ "blahblahblah", "183" },
{ "blehblehbleh", "184" },
{ "and so on...", "1000" }
}```
?
Thank you.
I wouldn’t use a dictionary the way you are, you could end up getting the wrong element down the line. Instead, I would just pass your JSON data into an array of a class which contains the data. Populate the dropdown options with the string name from each class indexed in the array and then get the array at that index.
1 Like
Hello,
Thanks,
But I used Newtonsoft “installing” the .DLL in Unity/Assets, and could do that:
using Newtonsoft.Json;
//download this https://github.com/JamesNK/Newtonsoft.Json/releases/download/12.0.2/Json120r2.zip
//then copy the Bin\net20\Newtonsoft.Json.dll to your Assets
So
var results = JsonConvert.DeserializeObject<List>(myJson);
myDic = new Dictionary<string, string>();
foreach (var myData in results)
{
myDic.Add(myData.description, myData.Id);
}
dropdown.AddOptions(myDic.Keys.ToList());
Just works with
[Serializable]
public class myData
{
public string Id;
public string description;
}
According to:
"
Why Json.Net ?
According to c# - Serialize and Deserialize Json and Json Array in Unity - Stack Overflow,
- Unity’s JsonUtility does not support array as it is still new.
- Unity’s JsonUtility can not serialize property.
- Unity’s JsonUtility can not serialize Dictonary.
so, Json.Net may be better.
Result
Thats it.