简体   繁体   中英

How to bind JSON response from httpClient.PostAsJsonAsync

I can httpClient.PostAsJsonAsync(path, content) fine.

However, this post returns some JSON with details of the response, eg: {"StatusCode":200,"AccessCode":"92BEEB285ZB47DA","InternalMessage":null}

I need to access the AccessCode.

How can I do this cleanly and efficiently? Can I create an object like this:

public class GIResponse
{
    public string StatusCode { get; set; }
    public string AccessCode { get; set; }
    public string InternalMessage { get; set; }
}

And map it to the result?

Or how would I just traverse the JSON and pull out the AccessCode?

I have searched quite extensively but surprisingly I can't find anything on Google - perhaps as this is the result from a Post, not a Get.

How can I do this?

Provided that you get the responseText using httpResponse.Content.ReadAsStringAsync , you can use Json.NET's JObject and define it as dynamic:

dynamic j = JObject.Parse(@"{""StatusCode"":200,""AccessCode"":""92BEEB285ZB47DA"",""InternalMessage"":null}");
Console.WriteLine(j.AccessCode);

Also you can use JsonConvert :

var result = JsonConvert.Deserialize<MyModel>(resposeText);

Obviously, if you already have a model, you do not read it as a string and you can simply read it as your model:

var result = httpResponse.Content.ReadAsAsync<MyModel>();

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