1

I am having some issue to deserialize the json from an API

I have tried HTTP Client and rest sharp both as well

   @page "/Demographics"
@using System
@using System.Collections.Generic
@using System.Diagnostics
@using System.Net.Http.Headers
@using System.Threading.Tasks
@using Microsoft.AspNetCore.Components
@using Newtonsoft.Json   
@inject HttpClient Http

<h3>Demographics</h3>
      <table class="table table-bordered">
    <thead>
    <tr>
        @foreach (var c in dyn.cols)
        {
            <td>@c.Value</td>

        }
    </tr>
    </thead>
    <tbody>
    @foreach (var r in dyn.rows)
    {
        <tr>
            @foreach (var d in r)
            {
                <td>@d.Value</td>

            }
        </tr>
    }
    </tbody>

</table>
@code
{
    dynamic dyn;
    //Patient[] patients;

    protected async Task OnInitAsync()
    {

        //patients = await Http.GetJsonAsync<Patient[]>("https://tsrvcis/cis-api/get-patient/by-mrn?format=json");

        var url = "https://tsrvcis/telemedicine-use-case";
        Http.DefaultRequestHeaders.Accept.Clear();
        Http.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        Http.DefaultRequestHeaders.Add("Authorization", "042a9ff198c04caf99161406f46eaf21|API Testing Script");
        var response = await Http.GetStringAsync(url);

        dyn = JsonConvert.DeserializeObject(response);
   }
}

The error i am getting: enter image description here

Expected result : There should be dynamic http table or grid. If there are UI plugin or any other solution that would be great.

DotNet Coder
  • 89
  • 1
  • 8

2 Answers2

1

Start with the following, try it, and come here with the new errors, if any:

<h3>Demographics</h3>

@if (dyn == null)
{
   <p>Loading...</p>
} 
else
{ 
      <table class="table table-bordered">
      ....

    </table>
}

Comments:

  • You have to ensure that the variable dyn is populated before it is used.

  • I'm not sure I understand why you're using dynamic type

  • Is the url OK: https://tsrvcis/telemedicine-use-case
  • This is a bearer token right: "042a9ff198c04caf99161406f46eaf21|API Testing Script"

  • Are you aware that the HttpClient service you're using is not the actual or real Httplient

  • Blazor is using System.Text.Json... So why use Newtonsoft.Json

enet
  • 41,195
  • 5
  • 76
  • 113
0

What I think is that you should make some initialization on the start, like

dynamic dyn = new {attr1 = new Object(), ...}

didn't write C# code for a while (pls fix this) but as I could remember, I got this error solved with initializing of object. P.S. he uses newtonsoft because of Blazor WebAPI to Client deserialization exception (PocoJsonSerializerStrategy)

mitotomi
  • 102
  • 9