ash moon
ash moon

Reputation: 47

Parsing nested JSON from cloud in dart but getting type error

I'm trying to to parse JSON from cloud, the data was received, I tried so many solution here in stackOverflow but the haven't work to me, I'm just string to get familiar with flutter and dart.

but i got this error:

type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<Category>'

here it is my code: JSON data I received: { "totalRowCount": 1, "pageSize": 100, "categories": [{ "CategoryName": "Beverages", "CategoryID": 1 }] }

Services.dart

import 'package:http/http.dart' as http;
import 'Category.dart';

class Services {
  static const String url = 'http://example.com/category';

  static Future<List<Category>> getCategories() async {
    http.Response response = await http.get(url, headers: {"Accept": "application/json"});
    if(response.statusCode == 200){
      final category = categoryFromJson(response.body);
      return category;
    } else{
      return List<Category>();
    }
  }
}

Category.dart

import 'dart:convert';
List<Category> categoryFromJson(String str) => List<Category>.from(json.decode(str));

class Category {
  Category({
    this.totalRowCount,
    this.pageSize,
    this.categories,
  });

  final int totalRowCount;
  final int pageSize;
  final List<CategoryElement> categories;

  factory Category.fromJson(Map<String, dynamic> json){
    return Category(
      totalRowCount: json["totalRowCount"],
      pageSize: json["pageSize"],
      categories: List<CategoryElement>.from(json["categories"]),
    );
  }

  Map<String, dynamic> toJson() => {
    "totalRowCount": totalRowCount,
    "pageSize": pageSize,
    "categories": List<dynamic>.from(categories.map((x) => x.toJson())),
  };
}

class CategoryElement {
  CategoryElement({
    this.categoryName,
    this.categoryId,
  });

  final String categoryName;
  final int categoryId;

  factory CategoryElement.fromJson(Map<String, dynamic> json) => CategoryElement(
    categoryName: json["CategoryName"],
    categoryId: json["CategoryID"],
  );

  Map<String, dynamic> toJson() => {
    "CategoryName": categoryName,
    "CategoryID": categoryId,
  };
}

any help

Upvotes: 0

Views: 165

Answers (1)

Tirth Patel
Tirth Patel

Reputation: 5746

You need to call jsonDecode on response.body to convert the response to a Map.

import 'dart:convert';

final category = Category.fromJson(jsonDecode(response.body));

Remove the following line, it's causing the issue. Decode it right away using the factory instead of creating another function. That function is invalid because List.from accepts an iterable and you're supplying a Map. Also, the json response is not a List.

List<Category> categoryFromJson(String str) => List<Category>.from(json.decode(str));

Upvotes: 1

Related Questions