How to transform a json object array into a list of objects in c# using Json.NET

Asked

Viewed 662 times

1

I’m starting to learn c# and I’m picking up to do this task, take an array of objects from a json and turn the elements of that array into objects of a specific type and put them in a list. Create a method that does this and returns a List of an object:

private List<Caneta> LerJsonCanetas()
{
    string sJson = null;
    JObject jObject = null;
    List<Caneta> arrCanetas = null;

    arrCanetas = new List<Caneta>();

    //lê o json
    sJson = File.ReadAllText(sArqConfiguracao); //sArqConfiguracao é o caminho para o arquivo json

    jObject = JObject.Parse(sJson);
    JArray sServer = (JArray)jObject["canetas"];

    IList<Caneta> server = jObject["canetas"].ToObject<Caneta[]>();

    foreach (Caneta caneta in server)
    {
        arrCaneta.Add(caneta);
    }

    return arrCaneta;
}

This is the method I created, it is not returning error, but the objects that are in the list are with null attributes, I wanted to know how to do so that I can get the objects that are in the json array and put in pen-like objects. I’m two days looking for how to do it and not get it yet. Can anyone help me? Thank you. Ah, this is my json:

    {
     "tempoexibicao": 10,
     "canetas":
      [
         {
            "cor" : "azul",
            "marca" : "bic"
         },
         {
            "cor" : "vermelha",
            "marca" : "pilot"
         }
      ]

    }

2 answers

1

Here’s an example that might help:

public class Minhaclasse
{
    public string tempoexibicao { get; set; }
    public IEnumerable<Canetas> canetas { get; set; }
}

public class Canetas
{
    public string cor { get; set; }
    public string marca { get; set; }
}

class Program {
   static void Main(string[] args)
   {
    string jsonString = @"{""tempoexibicao"": 10,""canetas"":[{""cor"" : ""azul"",""marca"" : ""bic""},{""cor"" : ""vermelha"",""marca"" : ""pilot""}]}";
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    Minhaclasse minhaClasse = serializer.Deserialize<Minhaclasse>(jsonString);
  }
}

1

Complementing Carlos' response, I also like to use Newtonsoft being like this:

  string jsonString = @"{""tempoexibicao"": 10,""canetas"":[{""cor"" : ""azul"",""marca"" : ""bic""},{""cor"" : ""vermelha"",""marca"" : ""pilot""}]}";
  var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<Minhaclasse>(jsonString);

Don’t forget to install the Newtonsoft Nuget package :)

Browser other questions tagged

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