Home > Blockchain >  How to access Json (which was a result of HttpMessage) in C#?
How to access Json (which was a result of HttpMessage) in C#?

Time:09-23

I am writing two applications (Web API's) in .NET . From the app A I want to call a method in Controller of app B using Http Request. Here

 using (var askPensionerDetails = new HttpClient())
            {
                double pensionToDisburse = 0;
                askPensionerDetails.BaseAddress = new Uri("http://localhost:55345/api/pensionerdetails/");
                var responseTask = askPensionerDetails.GetAsync("getById?pan="   inputOfPensioner.PAN);
                responseTask.Wait();
                var result =responseTask.Result ;
                if (result.IsSuccessStatusCode)
                {
                     var readTask = result.Content.ReadFromJsonAsync<object>();
                     readTask.Wait();
                     return Ok(readTask.Result);
                }
            }

The output for this in postman is

{
    "name": "bunk seenu",
    "dateOfBirth": "1990-01-02T00:00:00",
    "pan": "ABCD12351E",
    "salaryEarned": 45000,
    "allowances": 500,
    "pensionType": 1,
    "bankDetails": {
        "bankName": "SBI",
        "accountNumber": "SBI00001BS",
        "bankType": 0
    }
}

That was a desired output. But the problem is how to access the properties like bankdetails,name,pan,salaryEarned.

I have tried using readTask.Result["name"] but it is throwing error.

I have also tried using result.Content.ReadAsStringASync(); But the output in postman is

{
    "name": [],
    "dateOfBirth": [],
    "pan": [],
    "salaryEarned": [],
    "allowances": [],
    "pensionType": [],
    "bankDetails": [
        [
            []
        ],
        [
            []
        ],
        [
            []
        ]
    ]
}

I don't have class associated with the result type of Json for statement readTask = result.Content.ReadFromJsonAsync(); (As per design constraints).

CodePudding user response:

From the docs:

If you have JSON that you want to deserialize, and you don't have the class to deserialize it into, you have options other than manually creating the class that you need:

CodePudding user response:

You can use Newtonsoft.Json

JObject jo = JObject.FromObject(readTask.Result);
var name = jo["name"];
if(string.IsNnullOrEmpty(name)){
///some code 
}
  • Related