6

I am new to JSON, and want to make simple JSON object using StringBuilder which would be queried by a jQuery Ajax call.

[WebMethod]
public static string GetmyJSON()
{
    StringBuilder sb = new StringBuilder();       
    sb.Append("{firstname: \"Manas\",").Append("lastname : \"Tunga\"").Append("}");
    return sb.ToString();    

}

In my client-side code i have:

.ajax({

        type: "POST",
        url: "simplePage.aspx/GetmyJSON",           
        data: "{}",
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',

        success: function (data) {

            alert(data.d.firstname);             


        } // end of sucess

    }); // End of ajax

But my alert message shows 'undefined' instead of 'Manas'. Is it possible to return a JSON object using StringBuilder?

3
  • You can build proper .net object which encapsulates the data you want to send back and serailze them into JSON via some library like JSON.Net. If you want some in-built technique then do some research with DataContractSerializer Commented May 10, 2012 at 11:53
  • If you insist to make it this way, ether change the \" to ', ether change it to \\\" Commented May 10, 2012 at 11:55
  • 1
    JSON property names must be quoted, i.e.: {"id":10} Commented Oct 24, 2012 at 20:20

3 Answers 3

12

Never do that. Never build JSON manually. Always use JSON serializers. Or in your case you don't even need to do that because the ASP.NET webmethod runtime will take care. All you have to do is focus on your business requirements and don't worry about plumbing.

So for example start by defining a model that will represent your data:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

and then have your web method return this model leaving all serialization concerns to the framework:

[WebMethod]
public static Person GetPerson()
{
    Person p = new Person();
    p.FirstName = "Manas";
    p.LastName = "Tunga";
    return p;
}

And now simply consume this method from the client:

$.ajax({
    type: 'POST',
    url: 'simplePage.aspx/GetPerson',
    data: '{ }',
    contentType: 'application/json; charset=utf-8',
    success: function (data) {
        alert(data.d.FirstName);
        alert(data.d.LastName);
    }
});

No need to worry about JSON, string builders, ...

And you could also pass complex arguments to your web method if you needed to:

public class Foo
{
    public string Bar { get; set; }
}

and then:

[WebMethod]
public static Person GetPerson(Foo foo)
{
    ...
}

and finally:

$.ajax({
    type: 'POST',
    url: 'simplePage.aspx/GetPerson',
    data: JSON.stringify({ foo: { bar: 'baz' } }),
    contentType: 'application/json; charset=utf-8',
    success: function (data) {
        alert(data.d.FirstName);
        alert(data.d.LastName);
    }
});

The JSON.stringify method shown here is natively built into modern browsers. If you need to support legacy browsers you could include the json2.js script to your page.

Sign up to request clarification or add additional context in comments.

3 Comments

If i insist you to use string builder to manually create JSON then how would you do it. I wana know where was my mistake
You cannot insist on something as wrong as manually building JSON using strings. What is wrong is the approach that you have taken. The thing is that you are returning a string from your web method. So inside your success handler you need to parse this string back to an object if you want to access it, like this alert($.parseJSON(data.d).firstname);. But please, oh please promise me you will never do anything like that.
@DarinDimitrov, you are authoritative enough to just believe you and dismiss my performance concerns, but I'm still curious why is it bad and why there is no native JsonBuilder class in BCL in analogy to StringBuilder, XmlWriter, HtmlTextWriter. Why all those are OK, but JsonBuilder is evil? Let's say I need to create simple objects of 5 properties, but some properties should be defined only when some conditions are met. It's too complex to define models hierarchy for such case - I will use dynamic or Dictionary then. It will hurt performance a little...
3
var lstMes = new List<Person>();

            System.Web.Script.Serialization.JavaScriptSerializer oSerializer =
             new System.Web.Script.Serialization.JavaScriptSerializer();
                string sJSON = oSerializer.Serialize(lstMes);
                return sJSON;

dont forget to add reference to :

System.Web.Extensions.dll !!

Comments

0

Strictly answering the question -- yes you can return whatever you want from a .NET method. Your problem, as @canon said in a comment on the question, is probably that you must wrap the property names.

Which demonstrates why the "correct" answer (as already mentioned: 1, 2) is to use an existing serializer like JSON.NET (if you need to manually serialize) or let .NET handle it (like it does in most "recent" iterations) by returning the object itself.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.