6

How to deserialize this json array [{"i":737,"n":1}] to get the variable "i" e "n".

Class to deserialize

    class PortasAbertas {
  int i;
  int n;

  PortasAbertas({this.i, this.n});

  PortasAbertas.fromJson(Map<String, dynamic> json) {
    i = json['i'];
    n = json['n'];
  }

  Map<String, dynamic> toJson() {
    return {
      'i': i,
      'n': n
    };
  }
}

I'm trying deserialize the object using this code, but use it when dont have a array, but using array i don't know i can do it

   PortasAbertas objeto = new PortasAbertas.fromJson(responseJson);
     String _msg = ("Portas abertas: ${objeto.n}");

4 Answers 4

16
final List t = json.decode(response.body);
final List<PortasAbertas> portasAbertasList =
     t.map((item) => PortasAbertas.fromJson(item)).toList();
return portasAbertasList;

You can parse your JSON to list like that so you can use fromJson in an array.

Sign up to request clarification or add additional context in comments.

2 Comments

what if all the json comes back as the same name e.g. [ { "store": "AMAZON" }, { "store": "FLIPKART" }, { "store": "WALMART" }, { "store": "ALIBABA" }, ]
where does the method fromJson come from in PortasAbertas?
5

You can try using this lines,

List oo = jsonDecode('[{"i":737,"n":1},{"i":222,"n":111}]');
//here u get the values from the first value on the json array
print(oo[0]["i"]);
print(oo[0]["n"]);

//here u get the values from the second value on the json array
print(oo[1]["i"]);
print(oo[1]["n"]);

and for each value from your list, u have a json and can get access the value using "i" or "n";

Comments

0

I also faced the same issue but I solved using below code.

List jsonResult = jsonDecode(await RequestApiCallDemo().loadAsset());
for (var value in jsonResult) {
      ItemCategoryModel itemCategoryModel = ItemCategoryModel.fromJson(value);
      print("itemCategoryModel Item = " + itemCategoryModel.title);
}

If we convert json to dart we will only get Model that support Json-Object so the better approach is to do jsonDecode first and then insert object to your model

Comments

0

You can convert it to a List<dynamic> and map that list to fromJson of the model you expect.

final decoded = jsonDecode(json) as List<dynamic>;
final output = decoded
    .map((e) => ItemCategoryModel.fromJson(
        e as Map<String, dynamic>))
    .toList();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.