sly_Chandan
sly_Chandan

Reputation: 3515

How to serialise an object to json and send it to a web service?

How to serialise an object to json and send it to a web service?

var object = something....
function BindJson() {
        $.ajax({
            type: "POST",
            url: "NewPage.aspx/GetJson",
            data: "{}",
            contentType: "application/json",
            dataType: "json",
            success: function (data) {

            }
        })
    }

<body onload="BindJson();">

Server:

[WebMethod]
        public static string GetSerializedJsonObject()
        {
            return "";
        }

Upvotes: 1

Views: 11233

Answers (4)

NakedBrunch
NakedBrunch

Reputation: 49413

This will work for you (full working code sample below). The key is to pass in a Person object. Also, I used a simple web service (myService.asmx) instead of an aspx page. Why bother with the extra overhead if it isn't needed?

The key is, on the client, create a Person object and then use JSON.stringify to pass the Person object to the webservice.

Javascript

<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.js"></script>
<script type="text/javascript">
    function BindJson() {
        $.ajax({
            type: "POST",
            url: "myService.asmx/SerializeJson",
            data: JSON.stringify({ person:{ firstName: "Denny", lastName: "Cherian", department: "Microsoft PSS", address: { addressline1: "Microsoft India GTSC", addressline2: "PSS - DSI", city: "Bangalore", state: "Karnataka", country: "India", pin: "560028" }, technologies: ["IIS", "ASP.NET", "JavaScript", "AJAX"] }}),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data1) {
                alert(data1.d);
            },
            error: function (request, status, errorThrown) {
                alert(status);
            }
        });
    }

    $(document).ready(function() {
        BindJson();    
    });
</script>

C#

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

namespace TestProject
{
    /// <summary>
    /// Summary description for myService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class myService : System.Web.Services.WebService
    {

        [WebMethod]
        public string SerializeJson(Person person)
        {
            return "Success";
        }

        public class Person
        {
            public string firstName { get; set; }
            public string lastName { get; set; }
            public string department { get; set; }
            public Address address { get; set; }
            public string[] technologies { get; set; }
        }

        public class Address
        {
            public string addressline1 { get; set; }
            public string addressline2 { get; set; }
            public string city { get; set; }
            public string state { get; set; }
            public string country { get; set; }
            public string pin { get; set; }            
        }
    }
}

Upvotes: 3

Adriano Carneiro
Adriano Carneiro

Reputation: 58615

There's a question about it here: Basic Simple Asp.net + jQuery + JSON example

You should very easily adapt the code there to your needs. The only thing not clarified is how to serialize an object to JSON in the Javascript code, but that's already answered by Billa Ustad.

If you want to go further on the subject, there's an excellent and didactic article here: Full ASP.NET, LINQ, jQuery, JSON, Ajax Tutorial.

Remember: sometimes we just want to be given the fish, but eventually we gotta learn how to catch our own fish.

Upvotes: 0

Bilal Murtaza
Bilal Murtaza

Reputation: 795

you can use this

var myJSONText = JSON.stringify(myObject, replacer);

taken from

http://www.json.org/js.html

hope it helps.

Upvotes: 1

Yuck
Yuck

Reputation: 50855

Take a look at this MSDN article: JSON Serialization

Person p = new Person();
//Set up Person object...
MemoryStream stream1 = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Person));
ser.WriteObject(stream1, p);

The memory stream will contain...

{“age”:42,”name”:”John”}

Upvotes: 0

Related Questions