Json for List C#

Asked

Viewed 98 times

1

I have this Json (Json 1)

{
    "2": {
        "Data": "28/10/2019 12:50:26",
        "Id": 2,
        "Id_usuario": 0,
        "Latitude": -2,
        "Longitude": -52,
        "Portas": 8,
        "Status": "CHEIO"
    },
    "5": {
        "Data": "28/10/2019 12:39:33",
        "Id": 5,
        "Id_usuario": 0,
        "Latitude": -2,
        "Longitude": -66,
        "Portas": 8,
        "Status": "lIVRE"
    }
}

I realized that my code can read in this format (Json 2)

[
  {
    "Data": "28/10/2019 12:50:26",
    "Id": 2,
    "Id_usuario": 0,
    "Latitude": -2,
    "Longitude": -52,
    "Portas": 8,
    "Status": "CHEIO"
  },
  {
    "Data": "28/10/2019 12:39:33",
    "Id": 5,
    "Id_usuario": 0,
    "Latitude": -2,
    "Longitude": -66,
    "Portas": 8,
    "Status": "lIVRE"
  }
]

But from firebase Json comes in the format of the first code (Json 1) I’ve tried to use

List<Item_Caixa> caixas;

FirebaseResponse response = firebaseClient.Get(path);
JavaScriptSerializer js = new JavaScriptSerializer();
caixas = js.Deserialize<List<Item_Caixa>>(response.Body);// não funciona

caixas = JsonConvert.DeserializeObject<List<Item_Caixa>>(response.Body);// não funciona

My Class

public class Item_Caixa
{
        public int id { get; set; }
        public string status { get; set; }
        public int portas { get; set; }
        public double latitude { get; set; }
        public double longitude { get; set; }
        public string data { get; set; }
        public int id_usuario { get; set; }
}

I’ve looked at a lot of questions like this one at Stackoverflow, but none of the answers are working. What am I doing wrong?

2 answers

1

Hello, I believe that if you use the names of the json variables identical to the Item_box class.

   [
  {
    "data": "28/10/2019 12:50:26",
    "id": 2,
    "id_usuario": 0,
    "latitude": -2,
    "longitude": -52,
    "portas": 8,
    "status": "CHEIO"
  },
  {
    "data": "28/10/2019 12:39:33",
    "id": 5,
    "id_usuario": 0,
    "latitude": -2,
    "longitude": -66,
    "portas": 8,
    "status": "lIVRE"
  }
]

Using this way I believe that there will be a link between the attributes, because if you put to receive an objective type it will use these names as attributes, I believe that with the same names at the time of the cast to Item_box would work. I hope I’ve helped...

0

Try it like this:

List<Item_Caixa> caixas;

FirebaseResponse response = firebaseClient.Get(path);
 dynamic data  = JsonConvert.DeserializeObject<dynamic>(response.Body);

caixas = ((IDictionary<string, JToken>)data).Select(k =>
                JsonConvert.DeserializeObject<Item_Caixa>(k.Value.ToString())).ToList();
  • It worked. Thank you very much

Browser other questions tagged

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