Converting Jobject with dynamic objects

Asked

Viewed 31 times

0

I have been having this problem for some time, I need to take the values of the given object and add it in a list but I can’t 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’m trying is this but I can’t 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,

            });
        }

1 answer

0

Map the received JSON to a class and use the method Jsonconvert.Deserializeobject.

    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; }
}
  • From this error - Newtonsoft.Json.Jsonserializationexception: 'Error Converting value "0" to type

  • this small example helped me to solve what I needed

Browser other questions tagged

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