简体   繁体   English

解析从Web方法返回的字符串

[英]Parsing string returned from web method

I am developing a Windows Phone 8 C# app for the 1st time. 我是第一次开发Windows Phone 8 C#应用程序。

I am calling my web method I have defined in an aspx code-behind class. 我正在调用在aspx代码隐藏类中定义的Web方法。

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: str的值如下所示:

{"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? 我想我可以自己解析该字符串,但是JSON是否提供了一种更干净的方法?

Using Json.Net 使用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);
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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