Converting Jobject with Dynamic Objects

0

I've been having this little problem for some time, I need to get the values from the supplied object and add them to a list but I can not find a way to map them because they are coming dynamically

Array received

"respostas": {
  "0": {
    "codQuestao": "1",
    "codOpcao": "5",
    "texto": ")"
  },
  "1": {
    "codQuestao": "3",
    "codOpcao": "5",
    "texto": ")"
  },
  "2": {
    "codQuestao": "2",
    "codOpcao": "5",
    "texto": ")"
  },
  "3": {
    "codQuestao": "5",
    "codOpcao": "5",
    "texto": ")"
  },
  "4": {
    "codQuestao": "19",
    "codOpcao": "5",
    "texto": ")"
  },
  "5": {
    "codQuestao": "20",
    "codOpcao": "5",
    "texto": ")"
  },
  "6": {
    "codQuestao": "17",
    "texto": "testeetete"
  }
}

The code I am trying is this but I can not get the values

dynamic respostas = prova[0].respostas;
JObject itensRespostas = ((JObject)respostas);
        List<BOpcao> listaResposta = new List<BOpcao>();
        for(int i = 0; i<itensRespostas.Children().Count(); i++)
        {
            dynamic it = itensRespostas.Children()[i];
            Console.WriteLine("contagem :" + ''itensRespostas.Children().Count());
            string codQuestao = it.codQuestao;
            string texto = it.texto;
            string codOpcao = it.codOpcao;
            listaResposta.Add(new BOpcao()
            {
                CodOpcao = codOpcao,
                CodQuestao = codQuestao,
                Texto = texto,

            });
        }
    
asked by anonymous 20.07.2018 / 15:04

1 answer

0

Map the received JSON to a class and use the JsonConvert.DeserializeObject method.

    public List<Resposta> Deserializar(JObject respostas)
    {
        var itens = new List<Resposta>();

        foreach (var token in respostas.Children())
        {
            var r = JsonConvert.DeserializeObject<Resposta>(token.ToString());
            itens.Add(r);
        }

        return itens;
    }

The model class:

public class Resposta
{
    public string CodQuestao { get; set; }
    public string CodOpcao { get; set; }
    public string Texto { get; set; }
}
    
20.07.2018 / 17:49