How to transform an array of json objects into a List of objects in C # using Json.NET

1

I'm starting to learn C # and am getting to do this task, grabbing an array of objects from a json and transform 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 do I get the objects that are in the json array and put them in objects type pen. I'm two days away looking for how to do it and can not do it yet. Can someone help me? Thanks. Oh, this is my json:

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

    }
    
asked by anonymous 07.11.2017 / 19:58

2 answers

1

Here is 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);
  }
}
    
07.11.2017 / 20:29
1

Complementing Carlos's answer, I also like to use NewtonSoft thus:

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

Do not forget to install Newtonsoft's Nuget package:)

    
07.11.2017 / 21:56