android - 在Dart中从云中解析嵌套的JSON但出现类型错误

标签 android ios flutter dart

我正在尝试从云中解析JSON,收到了数据,
我在stackOverflow上尝试了很多解决方案,但对我没有用,我只是为了熟悉Flutter和Dart而已。
但是我得到了这个错误:

type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<Category>'
这是我的代码:
我收到的JSON数据:
{
“totalRowCount”:1,
“pageSize”:100,
“类别”:[{
“CategoryName”:“饮料”,
“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,
  };
}
任何帮助

最佳答案

您需要在jsonDecode上调用response.body,以将响应转换为Map

import 'dart:convert';

final category = Category.fromJson(jsonDecode(response.body));
删除以下行,这是导致问题的原因。立即使用工厂对其进行解码,而不是创建另一个函数。该函数无效,因为List.from接受可迭代,并且您正在提供Map。另外,json响应不是List
List<Category> categoryFromJson(String str) => List<Category>.from(json.decode(str));

关于android - 在Dart中从云中解析嵌套的JSON但出现类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64347170/

相关文章:

android - 如何在特定菜单项之间添加分隔符?

ios - 自定义声音远程推送通知 iOS 不工作

ios - 子类化 UICollectionReusableView : reference to "content area"

flutter - 尽管存在空检查,但 Dart 空安全性会提示函数变为空

java - 如何显示 Activity 中的数据库数据?

android - 如何将android的ImageButton样式应用到我自己的按钮上?

iphone - 依次异步调用MFMailComposeViewController

android - 应用程序终止时 Firebase 推送通知回调不起作用

flutter - 内置在不同文件/类中的访问变量

android - 如何一起使用mobile-ffmpeg和共享库(.so)ffmpeg?