你如何解析一个 JSON 对象数组?

瓦尔多康

谁能告诉我如何在颤振中解析对象数组的数组?当我解析 json 时,我收到错误消息type List<dynamic> is not a subtype of type Map<String, dynamic>.

我试图从 API 中获取要显示在屏幕上的数据,以便稍后构建一个 GridView 来显示所有产品及其各自的价格。

我从颤振文档中复制了大部分代码:https : //flutter.dev/docs/cookbook/networking/fetch-data

这是 API 的链接:https : //fakestoreapi.com/products/category/jewelery

我是一名学生,并试图尽可能多地学习,所以请尽可能具体:) 谢谢

代码:

    import 'dart:convert';
import 'package:flutter/widgets.dart';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';


class ProductPage extends StatefulWidget {
  const ProductPage({Key? key}) : super(key: key);

  @override
  _ProductPageState createState() => _ProductPageState();
}

class _ProductPageState extends State<ProductPage> {
  late Future<Album> futureAlbum;

  @override
  void initState() {
    super.initState();
    futureAlbum = fetchAlbum();
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          title: new Text("Accra Thrift"),
          backgroundColor: Color(0xff00eaff),
        ),
        body: new Center(

          child: FutureBuilder<Album>(
            future: futureAlbum,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return Text('${snapshot.data!.title}');
              } else if (snapshot.hasError) {
                return Text('${snapshot.error}');
              }

              // By default, show a loading spinner.
              return const CircularProgressIndicator();
            },
          ),
        ));
    // ),


  }
}

Future<Album> fetchAlbum() async {
  final response = await http
      .get(Uri.parse('https://fakestoreapi.com/products/category/jewelery'));

  if (response.statusCode == 200) {
    // If the server did return a 200 OK response,
    // then parse the JSON.
    return Album.fromJson(jsonDecode(response.body));
  } else {
    // If the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load album');
  }
}

class Album {
  final double price;
  final int id;
  final String title;

  Album({
    required this.price,
    required this.id,
    required this.title,
  });

  factory Album.fromJson(Map<String, dynamic> json) {
    return Album(
      price: json['price'],
      id: json['id'],
      title: json['title'],
    );
  }
}
帕特里克·马霍姆斯

当您查看您提供的链接中的 JSON 结构时,很明显它是一个地图列表,而不仅仅是一张地图。列表中的每个映射对应于 的一个实例Album这意味着您不只是在 API 调用中获取一张专辑,因此您不能像处理一张专辑一样处理响应。您需要返回 a List<Album>,例如:

Future<List<Album>> fetchAlbums() async {
  final response = await http
      .get(Uri.parse('https://fakestoreapi.com/products/category/jewelery'));

  if (response.statusCode == 200) {
    // If the server did return a 200 OK response,
    // then parse the JSON.
    dynamic data = jsonDecode(response.body);
    return data.map((element) => Album.fromJson(element)).toList();
  } else {
    // If the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load album');
  }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章