12/12/2016 10:26:38 PM
Viewed: 136
tamkhong
2/5/2013 4:59:47 PM
C# : Convert object to JSON string and JSON string to Object
using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;//System.Web.Extensions.dll

namespace JsonConverter
{
    class Program
    {
        static void Main(string[] args)
        {
            // convert json to obj
            string jsonStringSingle = "{'Id': 1, 'Name':'Thulasi Ram.S'}".Replace("'", "\"");
            var entity = new JavaScriptSerializer().Deserialize<IdName>(jsonStringSingle);
            
            string jsonStringCollection = "[{'Id': 2, 'Name':'Thulasi Ram.S'},{'Id': 2, 'Name':'Raja Ram.S'},{'Id': 3, 'Name':'Ram.S'}]".Replace("'", "\"");
            var collection = new JavaScriptSerializer().Deserialize<IEnumerable<IdName>>(jsonStringCollection);

            // convert obj to json
            var json = new JavaScriptSerializer().Serialize(entity);

            Console.WriteLine("Done...");
            Console.ReadKey(true);
        }
    }

    public class IdName
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}

Below is the JSON Syntax:

JSON Syntax Rules

JSON syntax is derived from JavaScript object notation syntax:

  • Data is in name/value pairs
  • Data is separated by commas
  • Curly braces hold objects ( {"firstName":"John", "lastName":"Doe"} )
  • Square brackets hold arrays ( "employees":[{"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"} ] )
A name/value pair consists of a field name (in double quotes), followed by a colon, followed by a value: "firstName":"John"

JSON Values

JSON values can be:

  • A number (integer or floating point)
  • A string (in double quotes)
  • A Boolean (true or false)
  • An array (in square brackets)
  • An object (in curly braces)
  • null

Gửi trả lời