How to make a simple JSON object using C # Builder string

I am new to JSON and want to make a simple JSON object using StringBuilder, which will be requested when jQuery Ajax is called.

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

}

In my client 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 warning message shows 'undefined' instead of 'Manas'. Is it possible to return a JSON object using StringBuilder?

+5
source share
3 answers

. JSON . JSON. , Webmethod ASP.NET . , , - .

, , , :

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

- , :

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

:

$.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);
    }
});

JSON, ,...

-, :

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

:

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

, :

$.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);
    }
});

JSON.stringify . , json2.js script .

+10
var lstMes = new List<Person>();

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

:

System.Web.Extensions.dll !!
+3

- , , , .NET-. , @canon , , .

, "" ( : 1, 2) , JSON.NET ( ) .NET ( "" ), .

0

All Articles