Tuesday, April 30, 2013

Convert jsonstring to c# list of objects

 
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            WebRequest request = WebRequest.Create("Your Service Path");
            // If required by the server, set the credentials.

            // Get the response.
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            // Get the stream containing content returned by the server.
            Stream dataStream = response.GetResponseStream();

            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.

            var responseFromServer = reader.ReadToEnd();
            
            string jsonString = responseFromServer;
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            DataResult collection = serializer.Deserialize<DataResult>(jsonString);

        }
    }
    

public class DataResult
{    
    [DataMember]
    public List<DataList> Data { get; set; }

}
[Serializable, DataContract]
public class DataList
{
    [DataMember]
    public string ID { get; set; }
    [DataMember]
    public string areaCode { get; set; }
    [DataMember]
    public string name { get; set; }

}

Note : Give the same name of class property which is match in json string like ID, areaCode, name and the Data which is in DataResult class.    

JsonString Exapmle :
 {"Data":[{"ID":"AF","areaCode":"93","name":"Afghanistan"}, {"ID":"AI","areaCode":"1","name":"Anguilla"}, {"ID":"AG","areaCode":"1","name":"Antigua and Barbuda"}, {"ID":"ZM","areaCode":"260","name":"Zambia"}, {"ID":"ZW","areaCode":"263","name":"Zimbabwe"}]}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.