正在从dart中的云解析嵌套JSON,但获取类型错误

我正试着从云中解析JSON,数据收到了,我尝试了很多stackOverflow的解决方案,但都没有用,我只是想熟悉一下颤动和飞镖。

但是我得到了这个错误:

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

这是我的代码:我收到的JSON数据:{ "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,
  };
}

有什么帮助吗?

转载请注明出处:http://www.kldfzc.com/article/20230526/947824.html