简体   繁体   中英

WebMethod returning JSON object issue

I am struggling to get object handled properly when returned from WebMethod. Conditions (my research after it):

Simple class to hold the properties:

    public class memberLogin
    {
    public string Username {get; set;}
    public string Password {get; set;}
    }

Serialization method:

        public static string JsonSerializer<T>(T t)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream();
            ser.WriteObject(ms, t);
            string jsonString = Encoding.UTF8.GetString(ms.ToArray());
            ms.Close();
            return jsonString;
        }

(simplified for clearness) Webmethod

    [WebMethod(EnableSession = true)]
    public static string getCredentials()
        {
            memberLogin ml = new memberLogin();
            ml.Username = "user";
            ml.Password = "pass";
            string json = JsonHelper.JsonSerializer<memberLogin>(ml);
            return json;
        }
        return null;
    }

And JavaScript

$("#element").live("click", function (e) { 

$.ajax({
    type: "POST",
    url: "Default.aspx/getCredentials",
    data: "{}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    async: false,
    cache: false,
    success: post_to_url
});
});
function post_to_url(params) {
method = "post";
path = "http://example";

var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);

for(var key in params) {
    if(params.hasOwnProperty(key)) {
        var hiddenField = document.createElement("input");
        hiddenField.setAttribute("type", "hidden");
        hiddenField.setAttribute("name", key);
        hiddenField.setAttribute("value", params[key]);

        form.appendChild(hiddenField);
     }
}
document.body.appendChild(form);
form.submit();
}

When debugging, WebMethod returns "{\\"Password\\":\\"pass\\",\\"Username\\":\\"user\\"}" so it seems to be what I want it to be (key, value par), except the \\ but that is how it is serialized. However when retrieved using ajax, I can not get any values out of it. alert(params) gives object Object , call to params.Username gives undefined . Is there something I am missing? Some sort of cast? I thought that if object is serialized, then there's no such need. Sorry for very long post but I tried to provide as much informations as I could.

You have to parse the JSON String into a JSON object. In Javascript:

var user = JSON.parse(params.responseText);
var username = user.Username;
var password = user.Password;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM