Home > Blockchain >  How to use class object instead of using JObject in .NET Core
How to use class object instead of using JObject in .NET Core

Time:05-15

I want to return C# class object instead of using JObject in here. Could someone can tell me how to use it.

private async Task<JObject> GetReceiptById(string Id, string name)
{
    var response = await _ApiService.Get(Id, name);
    var responseStr = await response.Content.ReadAsStringAsync();

    if (response.IsSuccessStatusCode)
    {              
        return JObject.Parse(responseStr);
    }

    throw new Exception(responseStr);
}

this method is return (return JObject.Parse(responseStr)); below JSON output. for that how to create a new class. I am not sure how to apply all in one class.

{
    "receipts": [
        {
            "ReceiptHeader": {               
                "Company": "DHSC",
                "ErpOrderNum": "730",                
                "DateTimeStamp": "2022-05-14T13:43:57.017"
            },
            "ReceiptDetail": [
                {
                    "Line": 1.0,
                    "ITEM": "PP1016",                    
                    "ITEM_NET_PRICE": 0.0
                },
                {
                    "Line": 2.0,
                    "ITEM": "PP1016",                    
                    "ITEM_NET_PRICE": 0.0
                }
            ],
            "XrefItemsMapping": [],
            "ReceiptContainer": [],
            "ReceiptChildContainer": [],
            "rPrefDO": {
                "Active": null,
                "AllowLocationOverride": null,                
                "DateTimeStamp": null
            }
        }
    ]
}

CodePudding user response:

What you probably looking for is Deserialization

you can achieve it with

var model = JsonConvert.Deserialize<YourClass>(responseStr);
return model;

but the class (YourClass) properties must match the json string you provided in responseStr.

CodePudding user response:

You can bind the Response Content to a known Type using ReadAsAsync<T>(). https://docs.microsoft.com/en-us/previous-versions/aspnet/hh835763(v=vs.118)

var result = await response.Content.ReadAsAsync<T>();

In your example you will also run into further issues as you are not closing your response after getting it from the Api Service Get method.

Below is a possible solution where you send your object type to the Get method. (not tested)


public virtual async Task<T> GetApiCall<T>(Id, name)
        {
            
            //create HttpClient to access the API
            var httpClient = NewHttpClient();
            //clear accept headers
            httpClient.DefaultRequestHeaders.Accept.Clear();
            //add accept json
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            //return the client for use

            using (var client = await httpClient )
            {
                //create the response
                HttpResponseMessage response = await client.GetAsync(url);
                if (response.IsSuccessStatusCode)
                {
                    //create return object
                    try
                    {
                        var result = await response.Content.ReadAsAsync<T>();
                        //dispose of the response
                        response.Dispose();
                        return result;
                    }
                    catch
                    {
                       throw;
                    }
                }
               // do something here when the response fails for example
                 var error = await response.Content.ReadAsStringAsync();
                 //dispose of the response
                 response.Dispose();
                 throw new Exception(error);
             }
          }
  • Related