Converting a JSON string to a .net Object

Overview

When building web apps we usually put our main functionality in a business layer. So lets say we have a website that lets our users add book suggestions. We will require the user to log into our site, so we know who the user is. To keep this simple we will have a form on that asks for the name of the book and a category. We will send this to our service, along with the user’s name and address using ajax.

The backend – Our .net classes

  • For this simple example, we will create three class objects: Address, Book, and BookSuggestion.
    Net Classes
    First we need the Address class:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace TestJSONObjects
    {
    	public class Address
    	{
    		public string Address1 { get; set; }
    		public string Address2 { get; set; }
    		public string City { get; set; }
    		public string State { get; set; }
    		public string Zip { get; set; }
    	}
    }
    

    Next we need Book.cs.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace TestJSONObjects
    {
    	public class Book
    	{
    		public string Name { get; set; }
    		public string Category { get; set; }
    	}
    }
    

    And finally the BookSuggestion class.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace TestJSONObjects
    {
    	public class BookSuggestion
    	{
    		public Address UserAddress { get; set; }
    		public Book SuggestedBook { get; set; }
    		public string UserName { get; set; }
    		public string Device { get; set; }
    	}
    }
    

  • The webpage

        
    	<form id="form1" runat="server">
        <input type="hidden" id="name" value="Kevin Gaddy" />
        <input type="hidden" id="Address1" value="123 Park Ave." />
        <input type="hidden" id="Address2" value="" />
        <input type="hidden" id="City" value="St. Louis" />
        <input type="hidden" id="State" value="MO" />
        <input type="hidden" id="Zip" value="12345" />
        <div>
            <h1>
                This is a Test</h1>
            <fieldset>
                <div>
                    <label id="lblName" for="txtBookName">
                        Book:</label>
                    <input type="text" id="txtBookName" />
                </div>
                <div>
                    <label id="lblCat" for="txtCategory">
                        Category:</label>
                    <input type="text" id="txtCategory" />
                </div>
          
                <div>
                </div>
            </fieldset>
        </div>
        </form>				
    

    As you can see we have some hidden fields that will hold the information that we collected when the user logged in. Next we have a form that will get the user’s book and category suggestion. Now we need to create the service that will collect the information.

  • I created a BookSuggestions.aspx to house our service method. Here is the code behind:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.Script.Serialization;
    using System.Web.Services;
    namespace TestJSON
    {
    	public partial class BookSuggestions : System.Web.UI.Page
    	{
    		[WebMethod(EnableSession = true)]
    		public static void AcceptObjectandDoSomething(string jsonString)
    		{
    			TestJSONObjects.BookSuggestion bs = new TestJSONObjects.BookSuggestion();
    
    			JavaScriptSerializer serializer = new JavaScriptSerializer();
    			bs = serializer.Deserialize<TestJSONObjects.BookSuggestion>(jsonString);
    			
    			if (bs == null)
    			{
    			}
    			else
    			{
    			}
    
    		}
    
    	}
    }
    

    So you see our method, AcceptObjectandDoSomething(string jsonString) will just accept a string from the ajax call. The first line in our method:

    TestJSONObjects.BookSuggestion bs = new TestJSONObjects.BookSuggestion();
    

    This creates an instance of the BookSuggestion object. Now we create a JavaScriptSerializer instance called serializer: JavaScriptSerializer serializer = new JavaScriptSerializer(); Now we use the serializer instance to convert the string that came into the method to the BookSuggestion object.

    bs = serializer.Deserialize<TestJSONObjects.BookSuggestion>(jsonString);
    

  • Now we can write our javascript to send the data to the service call.Lets create some object that will mirror our c# .net classes:

    var address = function(address1, address2, city, state, zip) {
    	this.address1 = address1;
    	this.address2 = address2;
    	this.city = city;
    	this.state = state;
    	this.zip = zip;
    }
    
    var book = function(name, category) {
    	this.name = name;
    	this.category = category;
    }
        	  
    var suggestion = function(address, book, userName, device) {
    	this.suggestedBook = book;
    	this.username = userName;
    	this.device = device;
    	this.userAddress = address;
    }
    

    It’s important that these classes have the same property names as their .net counterparts. The Ajax Method:

    $(document).ready(function() {
    	$('#addtoform').live('click', function() {
    
    		var myBook = new book($('#txtBookName').val(), $('#txtCategory').val());
    
    		var myAddress = new address($('#Address1').val(), $('#Address2').val(), $('#City').val(), $('#State').val(), $('#Zip').val());
         	//console.dir(myAddress);
    		var mySuggestion = new suggestion(myAddress, myBook, $('#name').val(), 'ipad');
        	//console.dir(mySuggestion);
    				
    
    		var jsonText = JSON.stringify(mySuggestion);
    		$.ajax({ type: "POST", url: "BookSuggestions.aspx/AcceptObjectandDoSomething", data: "{'jsonString':'" + jsonText + "'}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { console.dir(msg.d); } }); });
    }); 
    


    ajax

    post

    So you can see we are collecting the form info when the user clicks the #addtoform link.

    Now here is the important part:

    var jsonText = JSON.stringify(mySuggestion);

    posting This will make the javascript objects a JSON string that we can send to our service method. This is the string that the JavaScriptSerializer will convert to your business objects.


    incomming Source Code

Comments are closed.

 
UA-21428743-1