How to pick up items from a json in c#

Asked

Viewed 1,395 times

0

After almost 3 days trying to implement I did not succeed. I have the following json:

{ "code": 200,
 "data": [ 
 { "id": 1, "type": "charge", "custom_id": "1208", "status": { "current": "new", "previous": null }, "identifiers": { "charge_id": 542814 }, "created_at": "2018-12-03 11:15:24" }, 
 { "id": 2, "type": "charge", "custom_id": "1208", "status": { "current": "waiting", "previous": "new" }, "identifiers": { "charge_id": 542814 }, "created_at": "2018-12-03 11:15:28" } ] }

My goal is to get the item "status". The following code works well:

dynamic stuff1 = Newtonsoft.Json.JsonConvert.DeserializeObject(jo);
string Text = stuff1.data.status.current;

The code works to get the first line item, but how do I get the attribute "status" always on the last line, because it will always grow. I tried to use the .ToLast() to get the last record of "Current" but I’m not succeeding.

2 answers

3

First you need to create an object with the json-like structure for Jsonconvert to know where to map objects. According to this JSON will be something of the kind

public class RootObject
{
    public string Code { get; set; }
    public IList<Data> Data { get; set; }
}

public class Data
{
    public int Id { get; set; }

    public string Type { get; set; }

    [JsonProperty(PropertyName = "custom_id")]
    public string CustomerId { get; set; }

    public Status Status { get; set; }

    public Identifiers Identifiers { get; set; }

    [JsonProperty(PropertyName = "created_at")]
    public DateTime CreatedAt { get; set; }
}

public class Status
{
    public string Current { get; set; }
    public string Previous { get; set; }
}

public class Identifiers
{
    [JsonProperty(PropertyName = "charge_id")]
    public string ChargeId { get; set; }
}

Then just do the deserialization and get the last result:

var json = @" string com o json";
var res = JsonConvert.DeserializeObject<RootObject>(json);
var lastData = res.Data.LastOrDefault();
  • Antonio, thanks for the answer, he gave the following error: The best match of overloaded method 'Newtonsoft.Json.Jsonconvert.Deserializeobject<Siglaadministratión.Web.Query.Rootobject>(string)' has some invalid arguments

  • But I understood the logic you provided, I’ll implement here and I’ll tell you how it was.

  • The variable "string" is of type string and has there json?

2


The @António response is very well done, because it gives you a way to deserialize your JSON and turn into an object that you can use along the flow of your system.

I will give you an answer if you only need the attribute of the last line and do not want to do anything else with the other information, that is, if you do not need to use the other data you can follow the following alternative.

//Temos nosso JSON salvo nessa variável
string json = "{ \"code\": 200,\"data\": [{ \"id\": 1, \"type\": \"charge\", \"custom_id\": \"1208\", \"status\": { \"current\": \"new\", \"previous\": null }, \"identifiers\": { \"charge_id\": 542814 }, \"created_at\": \"2018-12-03 11:15:24\" },  { \"id\": 2, \"type\": \"charge\", \"custom_id\": \"1208\", \"status\": { \"current\": \"waiting\", \"previous\": \"new\" }, \"identifiers\": { \"charge_id\": 542814 }, \"created_at\": \"2018-12-03 11:15:28\" } ] }";

//Criamos nosso tipo anônimo apenas definindo as propriedades e seus tipos de dados que nos interessam
var anonymousType = new
{
    data = new[]
    {
        new
        {
            status = new
            {
                        current = ""
                    }
                }
            }
        };

// Pegamos o último elemento "data" e pegamos o valor do "current" caso ele exista.
var current = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(json, anonymousType)?.data?.LastOrDefault()?.status?.current;
  • Peter thanks for the answer, the deserialization was perfect!

  • You’re welcome, my dear =)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.