RestSharp Error :Giving null from the result.Data

csharp_new

New member
Joined
Apr 8, 2020
Messages
1
Programming Experience
3-5
I'm trying to fetch the data from rest api but getting null from the result.data

C#:
request4.AddHeader("Content-Type", "application/json");
request4.AddHeader("Authorization", "Bearer " + mytoken);
request4.AddParameter("application/json", "{ \"active\": true }", ParameterType.RequestBody);

var result = client4.Execute<List<RootObject>>(request4);//getting nullexcception here

//Console.WriteLine(result);
//Console.ReadKey();

foreach (var i in result.Data)
{
    foreach (var j in i.sales_offices)
    {
        Console.WriteLine(j.state);
    }
}

public class SalesOffice
{
    public bool active { get; set; }
    public string _id { get; set; }
    public string name { get; set; }
    public string state { get; set; }
}

public class RootObject
{
    public bool success { get; set; }
    public string message { get; set; }
    public List<SalesOffice> sales_offices { get; set; }
}
and from json I'm getting this result

JSON:
{ "success": true, "message": "Gtm Cities loaded successfully!", "sales_offices": [ { "active": true, "_id": "XXXXX5cb57542ed50d82730d7661d", "name": "UAXXS", "state": "AXXX.P" }

Please help me as it is showing no issue in the code
 
Last edited by a moderator:
Start by looking at the stack trace for the exception to see where the exception is actually being thrown, then debug that line to see which reference is null. That's how you ALWAYS diagnose a NullReferenceException.
 
If you catch the error, you can write-out the stacktrace to the console or debug window. This is why it's normally a good idea to start-off writing an error handler class for logging any and all exceptions your application has the potential to throw.
 
Assuming that the JSON given above is accurate, then it looks like the JSON is malformed. It seems to be truncated. It is missing some matching closing square and curly braces.
 

Latest posts

Back
Top Bottom