Wednesday, February 23, 2011

how to generate json file from .net object

    public class data_city
    {
        private string _city;

        public string city
        {
            get { return _city; }
        }

        public data_city(string city)
        {
            _city = city;
        }

    }


    public class data_state
    {
        public data_state(string id, string name)
        {
            _id = id;
            _name = name;
        }

        private string _id;

        public string id
        {
            get { return _id; }
        }
        private string _name;

        public string name
        {
            get { return _name; }
        }

        private List<data_city> _Cities = new List<data_city>();

        public List<data_city> cities
        {
            get { return _Cities; }
            set { _Cities = value; }
        }

    }


    private void GenerateJsonCities()
    {

        var state = from s in developerDataContext.States
                                orderby s.DisplayOrder
                                select new { id = s.StateCode, name = s.Description };



        List<data_state> dsl = new List<data_state>(); 
        foreach (var s in state)
        {
            data_state ds = new data_state(s.id, s.name);


            List<City> ss  = developerDataContext.Cities.Where(p => p.StateCode == s.id).OrderBy(p => p.City1).ToList();

            foreach (City c in ss)
            {
                ds.cities.Add(new data_city(c.City1));
            }

            dsl.Add(ds);

        }
       
           

        JavaScriptSerializer serializer = new JavaScriptSerializer();
        string json = serializer.Serialize(dsl);

        string city_json = string.Format("var data_state = {0};", json);

        File.WriteAllText(MapPath("~/scripts/referenceData/state_city.js"), city_json);

       

    }

3 comments:

cheap used hp computers said...

I am using JavaScript/jQuery for client side scripting. Now, I have a question here. When the user loads the page, a toolbar is loaded on the webpage at the bottom. While generating the toolbar, it has to send a request to the server to generate a JSON file.

http://www.usedhpcomputers.com/

andry said...

json is a very interesting language to be used. very good tutorial and can hopefully help me in building json in the application that I created for this lecture. thank you

yanmaneee said...

golden goose sneakers
nike air max 97
yeezy boost
adidas yeezy boost
air jordan
yeezy boost 350 v2
nike air max
fila
vans shoes
michael kors