Flutter : Can't get array json using dio to list of object
Asked Answered
L

2

12

I tried to load array json (array with no key) and fetch into list of object, here is my sample code :

My ApiCliet :

Future<List<OnBoardingModel>> fetchOnboarding() async {
    try {
      Response response = await dio.get("api/OnboardingItem");
      return OnBoardingModel.fromJson(response.data) as List;
    } catch (error, stacktrace) {
      throw Exception("Exception occured: $error stackTrace: $stacktrace");
    }
  }

My Object (generated using quicktype) :

List<OnBoardingModel> onBoardingModelFromJson(String str) => List<OnBoardingModel>.from(json.decode(str).map((x) => OnBoardingModel.fromJson(x)));

String onBoardingModelToJson(List<OnBoardingModel> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class OnBoardingModel {
  OnBoardingModel({
    this.id,
    this.judul,
    this.deskripsi,
    this.urlGambar,
  });

  int id;
  String judul;
  String deskripsi;
  String urlGambar;

  factory OnBoardingModel.fromJson(Map<String, dynamic> json) => OnBoardingModel(
    id: json["id"],
    judul: json["judul"],
    deskripsi: json["deskripsi"],
    urlGambar: json["urlGambar"],
  );

  Map<String, dynamic> toJson() => {
    "id": id,
    "judul": judul,
    "deskripsi": deskripsi,
    "urlGambar": urlGambar,
  };
}

In the end i got an error shown : Exception: Exception occured: type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>' stackTrace: #0, refer to this line return OnBoardingModel.fromJson(response.data) as List;

Could you please help me to solve this case. I thank you

Update

My json format :

[
  {
    "id": 0,
    "judul": "string",
    "deskripsi": "string",
    "urlGambar": "string"
  }
]
Logogriph answered 6/6, 2020 at 4:11 Comment(0)
L
40

Finally i got the answer, just replace the return using this :

return (response.data as List)
          .map((x) => OnBoardingModel.fromJson(x))
          .toList();

Complete code :

Future<List<OnBoardingModel>> fetchOnboarding() async {
    try {
      Response response = await dio.get("api/OnboardingItem");
      // if there is a key before array, use this : return (response.data['data'] as List).map((child)=> Children.fromJson(child)).toList();
      return (response.data as List)
          .map((x) => OnBoardingModel.fromJson(x))
          .toList();
    } catch (error, stacktrace) {
      throw Exception("Exception occured: $error stackTrace: $stacktrace");
    }
  }

Hope this answer helps other guests who new in flutter.

Logogriph answered 8/6, 2020 at 2:14 Comment(10)
Suprb, Working perfectTroy
@BaliCode will you please help me . I am stuck in a problem of listing data in flutter .Armoire
@jaspreetSingh will please help me . I am stuck in a problem of listing data in flutter.Armoire
I am getting the json response correctely but unable to list them.Armoire
@RahulKushwara : is there any error message appears?Logogriph
@RahulKushwaha Can u please show me your code and what response you're trying to parse? ThanksTroy
@Rahul : check the last paragraph of my question, i have attached the json that i tried to parseLogogriph
@BaliCodes My Json Format is like :{ "status": "ok", "totalResults": 8960, -"articles": [ -{ -"source": { "id": null, "name": "Moneycontrol" }, "author": null, "title": "String", "description": "String", "url": "String", "urlToImage": "String", "publishedAt": "sTRING", "content": "String" },]}Armoire
@jaspreetSingh I am using NewsApi.org json api. to get the results and show in list view ...using Dio . I am getting fine using http but fails to get using dio.Armoire
@RahulKushwaha can u please try with this code see below - return (response.data["articles"] as List) .map((x) => NewsResult.fromJson(x)).toList(); NewsResult is your model here.Troy
M
1

import 'dart:convert';

List<Welcome> welcomeFromJson(String str) => List<Welcome>.from(json.decode(str).map((x) => Welcome.fromJson(x)));

String welcomeToJson(List<Welcome> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Welcome {
    Welcome({
        this.id,
        this.judul,
        this.deskripsi,
        this.urlGambar,
    });

    int id;
    String judul;
    String deskripsi;
    String urlGambar;

    factory Welcome.fromJson(Map<String, dynamic> json) => Welcome(
        id: json["id"],
        judul: json["judul"],
        deskripsi: json["deskripsi"],
        urlGambar: json["urlGambar"],
    );

    Map<String, dynamic> toJson() => {
        "id": id,
        "judul": judul,
        "deskripsi": deskripsi,
        "urlGambar": urlGambar,
    };
}

final welcome = welcomeFromJson(jsonString);

Mcginty answered 6/6, 2020 at 6:40 Comment(3)
If not test your JSON output properlyMcginty
Still face this issue, sir. Exception: Exception occured: type 'List<dynamic>' is not a subtype of type 'String' stackTrace: #0Logogriph
Can you more details like API you are hitingMcginty

© 2022 - 2024 — McMap. All rights reserved.