Search code examples
jsonasp.net-web-apiparametersmodel-binding

using HttpClient in WinForms: can I parse JSON result using similar model binding as found in Web API


I guess I'm trying to interact with Web API as if these were the days of SOAP web service xml.. where a WSDL-based proxy CLR object was produced after talking to the server via HTTP. I'm not looking forward to walking a JSON response using JSON.NET, but, will if I have to.

So.. as we all know (all of us ASP.NET web devs) - we can use the Web API (and Web API 2, etc) to simply POST some JSON to an api controller and model binding (err.. parameter binding?) is capable of parsing that into my preferred CLR object.

Let's say I now have a WinForms client that wants to interact with my fancy Web API server - and I presume I ought to talk to that Web API using an HttpClient

Is there a preferred way to interact with the Web API to get a CLR object out of it? I presume I'm going to get JSON out of it that I must then bind to a CLR object... and that is my main question.. how can I do the same instantiation of a CLR-from-JSON on my client that I see happening when I'm posting the JSON up to the server.

The key term I didn't think of when I first wrote this question is 'deserialize'.. now I'm finding results like JsonConvert.DeserializeObject<MyObj>(json); and System.Web.Script.Serialization.JavaScriptSerializer

Still curious if there's a preference out there


Solution

  • You can (try to) read the response's content of HttpClient as any object. Here is a sample method

    public async Task<List<GroupListViewRow>> ListAccountGroupAsync(Guid ledgerId) {
            var response = await this.http.GetAsync($"v1/group/list?ledgerId={ledgerId}");
            response.EnsureSuccessStatusCode();
            var res = await response.Content.ReadAsAsync<List<GroupListViewRow>>();
            return res;
        }
    

    This one is reading the response as if it is List<GroupListViewRow>