Search code examples
jsonflutterdartparsingdio

I think parsing this type of json response is impossible in Dart. How can I convert this json to Dart Class?


An API gives me json response like this:

[{"version": "v3.5"}, {"setup": true}, {"address": "e7d398b"}, {"connected": true}, {"active": true}, {"id": "ce7143"}, {"genuine": true}]

As you can see, this is a list of objects. I tried parsing it like this using quicktype generated model class-

List<Result>.from(result.map((x) => Result.fromJson(x)));

But it's failing since each of the objects are of different types.

I think I have to convert each of the objects in the array one by one to Dart classes and add it to an Array.

So I tried this (I am using dio) -

final result = response.data;
var b = List.empty(growable: true);
result.map((x) => b.add(x));

But it's not working.

How can I atleast access the elements of the array?

Solved


Inspired by the accepted answer, I was able to generate corresponding Dart Class. Never thought can looping through a map is possible, IDE was not giving any clue.

final result = response.data;
      Map<String, dynamic> map = {};
      for (var e in result) {
        map.addAll(e);
      }
      final finalResult = Result.fromJson(map);
      return finalResult;

Solution

  • As Randal Schwartz mentioned above, there is no JSON you can not parse with Dart. In your case, you have a List of Map objects. What you can do is:

       final data = jsonDecode(json) as List;
    
        Map<String, dynamic> map = {};
    
        for (var e in data) {
          map.addAll(e);
        }
        print(map);
    
     //prints
    
    {version: v3.5, setup: true, address: e7d398b, connected: true, active: true, id: ce7143, genuine: true}
    
    

    If you're using the dio flutter package it returns decoded json, no need to call for jsonDecode. I recommend using json code generation if you face large json instead of relying on quicktype generated models.