简体   繁体   中英

Parsing string returned from web method

I am developing a Windows Phone 8 C# app for the 1st time.

I am calling my web method I have defined in an aspx code-behind class.

How do I parse the object returned please?

This is my return object:

public class ResponseObject
{
    public bool Success;
}

This is my test web method:

[WebMethod]
public static ResponseObject Test(string username, string password)
{
    ResponseObject responseObject = new ResponseObject();

    responseObject.Success= true;

    return responseObject;
}

This is my calling client code:

    private async void LogIn()
    {
        using (var client = new HttpClient())
        {
            var resp = await client.PostAsJsonAsync("http://my ip/UserManagement/Login.aspx/Test",
                                                     new { username = "", password = "" });
            var str = await resp.Content.ReadAsStringAsync();
        }
    }

This what the value of str looks like:

{"d":{"__type":"LogIn+ResponseObject","Success":true}}

I guess I could parse the string myself but does JSON offer a way to do this a bit more cleanly?

Using Json.Net

var str = await resp.Content.ReadAsStringAsync();
var jsonObj = JsonConvert.DeserializeObject<Response>(str);

public class D
{
    public string __type { get; set; }
    public bool Success { get; set; }
}

public class Response
{
    public D d { get; set; }
}

For future use cases you can define your own extension method

public static class SOExtensions
{
    public static async Task<T> ReadAsJsonAsync<T>(this HttpContent content)
    {
        var json = await content.ReadAsStringAsync();
        return JsonConvert.DeserializeObject<T>(json);
    }

}

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