C#: How to Serialize JSON Array data by c# on server side.

JSON: It is syntax for storing and exchanging text information. Much like XML. we can map JSON data to object.Here i have given example for mapping JSON array data to object.

Consider we have Json Array DataFormat below and we want to map these data to our StatusValueTest class:

 "[{ \"StatusValue\": \"Test1\", \"StatusValue1\": \"Test2\", \"StatusValue2\": \"Test3\", \"StatusValue3\": \"Test4\" },
 { \"StatusValue\": \"aTest1\", \"StatusValue1\": \"bTest2\", \"StatusValue2\": \"cTest3\", \"StatusValue3\": \"dTest4\"}]";

we have StatusValue ,StatusValue1, StatusValue2, StatusValue3,in array and we want to map it StatusValueTest Class data member StatusValue ,StatusValue1, StatusValue2, StatusValue3 Note: Here data member should be same as json data member otherwise it will give error.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;

    public class StatusValueTest
    {

        public StatusValueTest()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    public string StatusValue { get; set; }

    public string StatusValue1 { get; set; }

    public string StatusValue2 { get; set; }

    public string StatusValue3 { get; set; }
    }

JavaScriptSerializer :Provides serialization and deserialization functionality for JSON data.For Mapping Between Managed Types and JSON we create first JavaScriptSerializer object and used its Deserialize  method for Deserialize Json data. See in below code:

    string strJSONData = "[{ \"StatusValue\": \"Test1\", \"StatusValue1\": \"Test2\", \"StatusValue2\": \"Test3\", \"StatusValue3\": \"Test4\" }, { \"StatusValue\": \"aTest1\", \"StatusValue1\": \"bTest2\", \"StatusValue2\": \"cTest3\", \"StatusValue3\": \"dTest4\"}]";

    JavaScriptSerializer objJavaScriptSerializer = new JavaScriptSerializer();

    StatusValueTest[] objStatus = objJavaScriptSerializer.Deserialize<StatusValueTest[]>(strJSONData);

    foreach (StatusValueTest val in objStatus)
       {
         Label1.Text += val.StatusValue;
       }

OutPut:Test1aTest1

Advertisements

One thought on “C#: How to Serialize JSON Array data by c# on server side.

  1. Pingback: How to Parse JSON Date on client side by java script. | [Code Destination]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s