Search code examples
c#jsonasp.net-coredotnet-httpclient

Deserialize JSON of unknown type in ASP.NET Core C#


I am writing an ASP.NET Core service that's a basic passthrough for now. It should receive JSON from another server and send it to the client as is.

Let's say the other server serves this:

[{"id":1,"name":"Sleep","isComplete":false}]

my passthrough calls HttpClient.GetStringAsync the problem is that it returns a string not an object :

 "[{\"id\":1,\"name\":\"Sleep\",\"isComplete\":false}]"

That's not what I need. So how do I get the original? I do not see a GetXXX method in HttpClient that will return arbitrary object (that would be plan A). I tried HttpClient.GetAsync but that does not return the JSON either it returns HttpResponseMessage that contains everything (headers status etc.) EXCEPT the desired JSON
Plan B is to convert the string into an object but even if I ignore extra cycles spent on it, I don't know the object type in advance. I tried Newtonsoft's

JsonConvert.DeserializeObject<dynamic>

and also

JObject.Parse 

neither worked. I also tried RegEx.Unescape - no dice.
Is HttpClient may be not the right tool for this? Or am I using it wrong?


Solution

  • if you use net 6+ minimal api

    using Microsoft.AspNetCore.Http;
    
     var jsonString = "[{\"id\":1,\"name\":\"Sleep\",\"isComplete\":false}]";
      
      return Results.Content(jsonString, "application/json");
    
    

    else

    using Microsoft.AspNetCore.Mvc;
    
      return Content(jsonString, "application/json");