- Home /
Populate JSON data to dropdown list
I have a JSON file with cities from Openweathermap. And want to put cities names into dropdown list. How to do this?
Example
{
"id": 2163306,
"name": "Holgate",
"country": "AU",
"coord": {
"lon": 151.416672,
"lat": -33.400002
}
},
{
"id": 2164949,
"name": "Gooramadda",
"country": "AU",
"coord": {
"lon": 146.550003,
"lat": -36
}
},
{
"id": 2157716,
"name": "Miepoll",
"country": "AU",
"coord": {
"lon": 145.466675,
"lat": -36.616669
}
},
{
"id": 2148406,
"name": "Steiglitz",
"country": "AU",
"coord": {
"lon": 144.183334,
"lat": -37.883331
}
},
Comment
Answer by Schmit · Jun 29, 2019 at 12:32 AM
You'll probably want to use a Json deserializer, like Unity's built-in JsonUtility (an alternative is Newtonsoft, which I find to be more reliable/robust feature-wise), then pass in dropdown options based on each item's name
field.
Load text:
var content = "";
using (var stream = new FileStream(absolutePath, FileMode.Open))
{
using (var reader = new StreamReader(stream))
{
content = reader.ReadToEnd();
}
}
Deserialize:
[System.Serializable]
public class OpenWeatherCity
{
public int id;
public string name;
public string country;
}
var cities = JsonUtility.FromJson<List<OpenWeatherCity>>(content);
Dropdown options:
var dropdownOptions = cities.Select(x => new Dropdown.OptionData(x.name)).ToList();
this.dropdown.AddOptions(dropdownOptions);
Your answer
![](https://koobas.hobune.stream/wayback/20220612204007im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Enums as a dropdown in inspector in C# 2 Answers
Drop down with sizes 1 Answer
Use of Dropdown layout element as listbox 0 Answers
TextMeshPro to Dropdown menu 2 Answers
MouseLook FPS Sensitivty (DropDown) 0 Answers