Rotten Code

it can always work better - but at least it should work

  Home  |   Contact  |   Syndication    |   Login
  18 Posts | 0 Stories | 12 Comments | 2 Trackbacks

News



Archives

Recommended Podcasts

Thursday, February 18, 2010 #

So you want to read a string (say, from a file or just passed in as a variable) into a .NET class. Here's a quick example of how to do this.

Let's start with our sample JSON:

{"FirstName":"Joe","LastName":"Smith","MiddleName":"Anthony"}

So to keep this simple, let's say we want to populate a class with this data.

our class:

public class Person
    {
        private string _FirstName;
        private string _LastName;
        private string _MiddleName;

        public string FirstName
        {
            get { return this._FirstName; }
            set { this._FirstName= value; }
        }

        public string LastName
        {
            get { return this._LastName; }
            set { this._LastName= value; }
        }

        public string MiddleName
        {
            get { return this._MiddleName; }
            set { this._MiddleName= value; }
        }
  
    }

 

Here's our method to populate this class in C#:

using System.IO;

using System.Web.Script.Serialization;

 

public void ReadJSON(string jsonInput)

{

  JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();

  Person singlePerson  = jsonSerializer.Deserialize<Person>(jsonInput)

}