Tushar Kanta Prusty Tushar Kanta Prusty - 6 months ago 22
JSON Question

Not able to access particular data from a List<Rootobject> object

I have a json file, which I have deserialized and added the data to

List<Rootobject>
.

The json file is as below.

{"_id":707860,"name":"Hurzuf","country":"UA","coord":{"lon":34.283333,"lat":44.549999}}
{"_id":519188,"name":"Novinki","country":"RU","coord":{"lon":37.666668,"lat":55.683334}}
{"_id":1283378,"name":"Gorkhā","country":"NP","coord":{"lon":84.633331,"lat":28}}

It has 2,00,000 such rows.

I have deserialized it as below.

public List<Rootobject> list=new List<Rootobject>();
public List<Rootobject> ReadAllCities()
{
var lines = File.ReadAllLines("Assets/city_list.json");
foreach (var line in lines)
{
var res = JsonConvert.DeserializeObject<Rootobject>(line);
list.Add(res);
}
return list;
}


Now I want to just retrieve the "name" property from the list and create a
List<String>
object. I am trying to do that using
foreach
. But I am getting compilation error.

It says Rootobject does not contain a definition for name.

Please help...

Answer

Assuming Rootobject is defined as...

public class Rootobject {
    public int _id { get; set; }
    public string name { get; set; }
    public string country { get; set; }
    public Coord coord { get; set; }
}

and list is...

public List<Rootobject> list = new List<Rootobject>();

populated with objects.

You can use LINQ to select the name

List<string> namesList = list.Select(i => i.name).ToList();

or if you want to use foreach...

List<string> namesList = new List<string>();
foreach(var item in list) {
    string name = item.name;
    namesList.Add(name);
}