0

I have a JSON file with cities from Openweathermap. And want to put cities names into dropdown list in Unity, using C#. How to do this?

JSON file

{
     "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
     }
   },
Alina
  • 424
  • 1
  • 4
  • 17
  • Possible duplicate of [Serialize and Deserialize Json and Json Array in Unity](https://stackoverflow.com/questions/36239705/serialize-and-deserialize-json-and-json-array-in-unity) – derHugo Jul 01 '19 at 06:20

1 Answers1

0

Using Unity's JsonUtility you will have to define the full structure before you can deserialize it.

[Serializable]
public class Data
{
    public string id;
    public string name;
    public string country;
    public Coord coord;
}

[Serializable]
public class Coord
{
    public float lon;
    public float lat;
}

Data myData = JsonUtility.FromJson<Data>(json);

Personally, I prefer to use Json.Net when you're only interested in a part of the json structure.

You would be able to do the following instead:

JObject jRoot = JObject.Parse(json);
foreach (JObject jCity in jRoot)
{
    string cityName = jCity["name"].Value<string>();
    // add cityName to drop down list
}
Iggy
  • 4,767
  • 5
  • 23
  • 34
  • Your first solution won't work here since the output is supposed to be an array but your `Data` type only can hold the information of one single entry – derHugo Jul 01 '19 at 06:21
  • @derHugo oh yeah you're right. I'm curious now, how would you make an object that contains other objects, without explicitly creating a variable for each one? – Iggy Jul 01 '19 at 08:48
  • using an [array](https://stackoverflow.com/questions/36239705/serialize-and-deserialize-json-and-json-array-in-unity) ;) – derHugo Jul 01 '19 at 08:51
  • @derHugo I mean, when you don't have the control over JSON format, like the weather data. – Iggy Jul 01 '19 at 08:52
  • did you even look at the link? It is all described there. In this case e.g. I would maybe go for adding `{"items" : [ JSONSTRING ]}` so you can simply deserialize it to a class `[Serializable] public class DataItems { public Data[] items; }` – derHugo Jul 01 '19 at 09:07
  • @derHugo ah sorry, I skimmed through it. Yeah, that makes sense now. Thanks for linking :) – Iggy Jul 01 '19 at 09:24