Converting C# object to Json and Json object to C#

For this we need to add newtonsoft.json.net20

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Newtonsoft.Json;
using System.Web.Script.Serialization;

namespace WindowsFormsApplication2
    public partial class Form1 : Form
        public Form1()

        private void Form1_Load(object sender, EventArgs e)

        private void button1_Click(object sender, EventArgs e)
            Credentials c = new Credentials();
            c.UserName = "Chikkanti";
            c.PassWord = "Venki";
            string ans = JsonConvert.SerializeObject(c, Formatting.Indented);
            textBox1.Text = ans;

        private void button2_Click(object sender, EventArgs e)
            JavaScriptSerializer json_serializer = new JavaScriptSerializer();
            Dictionary<string, object> credentials =
                   (Dictionary<string, object>)json_serializer.DeserializeObject(textBox3.Text);//TextBox3 Contains Json Text
            List<Credentials> obj = new List<Credentials>();
            foreach (var item in credentials)
                if (item.Key == "UserName")
                    obj.Add(new Credentials { UserName = item.Value.ToString() });
                else if (item.Key == "PassWord")
                    obj.Add(new Credentials { PassWord = item.Value.ToString() });
            string s = string.Empty;
            foreach (Credentials c in obj)
                s += c.UserName + "  " + c.PassWord;
            textBox2.Text = s;
    public class Credentials
        public string UserName;
        public string PassWord;
        public void setTest(String prUserName) { UserName = prUserName; }

Converting C# object to json viceversa



Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s