Reputation: 384
I was trying to get data using geonames api and then find only the names of city.
http://api.geonames.org/searchJSON?username=ksuhiyp&country=in&maxRows=10&style=SHORT.
I got the data but it is in json and i could not find a way to get only names of cities in string format. Code used-
var data = (JObject)JsonConvert.DeserializeObject(ResultInCSV);
string cityname= data["name"].Value<string>();
string cityname= cityname.Split('\n')[0];
//JObject obj = JObject.Parse(ResultInCSV);
//string FirstLine = (string)obj["name"];
Please guide me in getting the name of city from this json.
Json result after clicking on link-
{
"totalResultsCount": 578584,
"geonames": [{
"lng": "72.88261",
"geonameId": 1275339,
"countryCode": "IN",
"name": "Mumbai",
"toponymName": "Mumbai",
"lat": "19.07283",
"fcl": "P",
"fcode": "PPLA"
}, {
"lng": "88.36304",
"geonameId": 1275004,
"countryCode": "IN",
"name": "Kolkata",
"toponymName": "Kolkata",
"lat": "22.56263",
"fcl": "P",
"fcode": "PPLA"
}, {
"lng": "77.59369",
"geonameId": 1277333,
"countryCode": "IN",
"name": "Bengaluru",
"toponymName": "Bengaluru",
"lat": "12.97194",
"fcl": "P",
"fcode": "PPLA"
}, {
"lng": "79",
"geonameId": 1269750,
"countryCode": "IN",
"name": "India",
"toponymName": "Republic of India",
"lat": "22",
"fcl": "A",
"fcode": "PCLI"
}, {
"lng": "80.27847",
"geonameId": 1264527,
"countryCode": "IN",
"name": "Chennai",
"toponymName": "Chennai",
"lat": "13.08784",
"fcl": "P",
"fcode": "PPLA"
}, {
"lng": "77.23149",
"geonameId": 1273294,
"countryCode": "IN",
"name": "Delhi",
"toponymName": "Delhi",
"lat": "28.65195",
"fcl": "P",
"fcode": "PPLA"
}, {
"lng": "78.45636",
"geonameId": 1269843,
"countryCode": "IN",
"name": "Hyderabad",
"toponymName": "Hyderabad",
"lat": "17.38405",
"fcl": "P",
"fcode": "PPLA"
}, {
"lng": "72.58727",
"geonameId": 1279233,
"countryCode": "IN",
"name": "Ahmedabad",
"toponymName": "Ahmedabad",
"lat": "23.02579",
"fcl": "P",
"fcode": "PPL"
}, {
"lng": "73.85535",
"geonameId": 1259229,
"countryCode": "IN",
"name": "Pune",
"toponymName": "Pune",
"lat": "18.51957",
"fcl": "P",
"fcode": "PPL"
}, {
"lng": "77.22445",
"geonameId": 1261481,
"countryCode": "IN",
"name": "New Delhi",
"toponymName": "New Delhi",
"lat": "28.63576",
"fcl": "P",
"fcode": "PPLC"
}
]
}
Upvotes: 1
Views: 734
Reputation: 999
You can get this way:
List<string> citynames=new List<string>();
for(i=0;i<data.Length;i++)
{
citynames.Add(data.geonames[i].name);
}
Upvotes: 0
Reputation: 930
You can use any of below method to get the list of city names:
var jo = JObject.Parse(jsonString);
var a =jo["geonames"].Select(city => city["name"].ToString()).ToList();
//Or
foreach (var cityInfo in jo["geonames"])
{
Console.WriteLine(cityInfo["name"]);
}
Upvotes: 0
Reputation: 6864
The following line of code will give you a list of city names
IList<string> cityNames = data["geonames"].Select(gn => gn["name"].ToString()).ToList();
Upvotes: 1