C# Json facile

Add System.Data.DataSetExtensions in reference
.net 4.5

/// Add System.Data.DataSetExtensions

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization; 

namespace json.net
{
    class Program
    {
        static void Main(string[] args)
        {
            Employee emp = new Employee()

            {
                Name = "Omer",
                PhoneNumber = "+3245678911"
            };

            List<string> myemails = new List<string>();
            myemails.Add(@"jfortias.net@gmail.com");
            myemails.Add(@"contact@jfortias.net");
            emp.Emails = myemails;

            List<Address> myaddresses = new List<Address>();
            Address add1 = new Address(){ StreetName = "Rue de Bistrot", Number = 1, ZipCode = "B-1040", City = "Etterbeek", Country = "Belgique" };
            Address add2 = new Address() { StreetName = "Rue des Pub", Number = 2, ZipCode = "B-1040", City = "Etterbeek", Country = "Belgique" };

            myaddresses.Add(add1);
            myaddresses.Add(add2);

            emp.Addresses = myaddresses;

            JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
            string jsonString = jsSerializer.Serialize(emp);
            Console.WriteLine(jsonString);    

            Employee empObj = jsSerializer.Deserialize<Employee>(jsonString);
            string name = empObj.Name;
            string phone = empObj.PhoneNumber;
            Console.WriteLine("Name is: "+ name);
            Console.WriteLine("Phone Number is: " + phone);

            foreach (string email in empObj.Emails)
            {
                Console.WriteLine(email);
            }

            foreach (Address myitem in empObj.Addresses)
            {
                Console.WriteLine("Address : {0}, {1} - {2} {3 } - {4}", myitem.StreetName, myitem.Number, myitem.ZipCode, myitem.City, myitem.Country);
            }
            Console.ReadKey();
            Console.WriteLine("END");
        }
    }

    public class Employee
    {
        public string Name { get; set; }
        public string PhoneNumber { get; set; }
        public List<string> Emails { get; set; }
        public List<Address> Addresses { get; set; }
    }

    public class Address
    {
        public string StreetName { get; set; }
        public int Number { get; set; }
        public string City { get; set; }
        public string ZipCode { get; set; }
        public string Country { get; set; }
    }
   

}


Commentaires