Jamie Jamie - 2 months ago 19
JSON Question

C# loading grid with json

I'm trying to load a grid with json that I receive. This is my code in

Home.cs
:

private void getTickets()
{
try
{
string urlName = "tickets";
string method = "GET";
string json = null;
HttpStatusCode statusCode = HttpStatusCode.Forbidden;
Tickets data = null;

RestClient client = RequestClient.makeClient();
MakeRequest request = new MakeRequest(null, null, urlName, method);

IRestResponse response = client.Execute(request.exec());

statusCode = response.StatusCode;
json = response.Content;
var ticketWrapper = JsonConvert.DeserializeObject<TicketWrapper>(json);

if ((int)statusCode == 200)
{
gridTicket.DataSource = ticketWrapper.tickets;
}

else
{
MessageBox.Show("error");
}
}

catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}


Ticket wrapper class

class TicketWrapper
{
public IEnumerable<Tickets> tickets { get; set; }
}


Tickets class

class Tickets
{
public int id;
public string title;
public string description;
public int user_id;
public int subject_id;
}


If I debug I can see that I receive the json but
ticketWrapper
is null what could be wrong here?

Debug image:enter image description here

Answer

Try to change public fields in Ticket class to properties:

class Tickets
{
    public int id { get; set; }
    public string title { get; set; }
    public string description { get; set; }
    public int user_id { get; set; }
    public int subject_id { get; set; }
}

Also I think that IEnumerable is not the best option for serialization. Try to use List in TicketWrapper.

Additionally move your break point down, because in current position ticketWrapper will be always null (expression has not yet been executed).