What I have
This code calling my API:
HttpResponseMessage response = await Http.GetAsync("https://localhost:7094/api/MyResource/94d0e5ca-2be7-42f7-94dc-13955c11595c");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine($"RESPONSE: {responseBody}");
var payload = JsonSerializer.Deserialize<MyClass>(responseBody);
var json = JsonSerializer.Serialize(payload);
Console.WriteLine($"PAYLOAD: {json}");
This code is called from OnInitializedAsync
in a NET8 Blazor WASM client.
The response I get
The first WriteLine of the responseBody returns this:
{
"creationOptions": 0,
"id": 226,
"isCanceled": false,
"isCompleted": true,
"isCompletedSuccessfully": true,
"isFaulted": false,
"result": {
"content": {
<Actual content>
},
"links": {
<my hateoas links>
}
},
"status": 5
}
That is correct.
What’s failing
The deserialize of MyClass does not seem to happen correctly, because the second writeline returns this:
PAYLOAD: null
That’s not unsurprising because the responseBody has added the http get results. I need to go down the json tree once.
I can’t do:
var payload = JsonSerializer.Deserialize<MyClass>(responseBody.result);
Because responseBody is of type string, as you can see above.
I have also tried
to use
var payload = Http.GetFromJsonAsync<Payload<MyClass>>("https://localhost:7094/api/MyResource/94d0e5ca-2be7-42f7-94dc-13955c11595c");
But that returns:
{ "content": null, "links": null }
I suspect that’s a timing issue (data is not ready yet when I writeline).
What’s the best way to get my actual payload from the json responseBody?
2
Answers
You can try:
Not a full answer but:
It seems that you need to fix your
https://localhost:7094/api/MyResource/94d0e5ca-2be7-42f7-94dc-13955c11595c
endpoint first. It seems that for some reason you are returning/serializingTask<TResult>
instead ofTResult
which leads to the corresponding output. There are multiple possible reasons for that, like missingawait
in the code, or incorrect value used for serialization (the code for endpoint is needed for more precise advice).That is actually surprising, since the response contains a JSON object, an non-null instance of
MyClass
should be deserialized to a non-nullable instance, though it properties obviously would not be correctly filled.Also if you are not actually serializing
System.Task<TResult>
instance then you can always create a container and use it for deserialization. Something along these lines: