CityPeople Serialization

CSharp · Console

/Program.cs

using System;
using Newtonsoft.Json;
using System.Collections.Generic;

					
public class Program
{
	static string json = "{\"italy\":[{\"city\":\"rome\",\"people\":100000},{\"city\":\"milan\",\"people\":50000}],\"spain\":[{\"city\":\"barcelona\",\"people\":100000},{\"city\":\"madrid\",\"people\":2000}]}";

	public static void Main()
	{
		List<CityPeople> cityPeople = new List<CityPeople>();
		foreach(var f in JsonConvert.DeserializeObject<Dictionary<string, CityInfo[]>>(json))
		{
			foreach(var i in f.Value)
			{
				cityPeople.Add(new CityPeople() {
					City = i.City,
					Country = f.Key,
					People = i.People
				});
			}
		}
		
		foreach(var c in cityPeople)
		{
			Console.WriteLine("{0}", c.Country);
			Console.WriteLine("-{0}", c.City);
			Console.WriteLine("-{0}", c.People);
		}
		
	}
	
	public class CityInfo
	{
		public string City { get; set; }
		public int People { get; set; }
	}
	
	public class CityPeople
    {
        public string City { get; set; }
        public string Country { get; set; }
        public int People { get; set; }
    }
}
;