Home > Enterprise >  I think parsing this type of json response is impossible in Dart. How can I convert this json to Dar
I think parsing this type of json response is impossible in Dart. How can I convert this json to Dar

Time:12-27

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?

CodePudding user response:

There's no JSON that isn't parsable with Dart. But you might end up with a data structure that requires careful navigation. Classes make it easier, but there isn't always a class structure for any arbitrary JSON, and maybe that's your point. In that case, you'll have to navigate to the data of interest in an ad-hoc fashion.

CodePudding user response:

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.

  • Related