json 错误:List<dynamic> 不是 Map<String, dynamic> 类型的子类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51854891/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 19:08:36  来源:igfitidea点击:

Error: List<dynamic> is not a subtype of type Map<String, dynamic>

jsonflutter

提问by Asyraf Dayan

I am currently building an app to read data through an api and I am trying to parse a JSON api from JSON Placeholder.

我目前正在构建一个应用程序来通过 api 读取数据,我正在尝试从 JSON Placeholder 解析 JSON api。

I made a model class for the Users (users_future_model.dart):

我为用户创建了一个模型类(users_future_model.dart):

class Users {
  final int userID;
  final String name;
  final String username;
  final String email;
  final Address address;

  Users({this.userID, this.name, this.username, this.email, this.address});

  factory Users.fromJson(Map<String, dynamic> usersjson)=> Users(
      userID: usersjson["id"],
      name: usersjson["name"],
      username: usersjson["username"],
      email: usersjson["email"],
      address: Address.fromJson(usersjson["address"])
  );
}

class Address{

  final String street;
  final String suite;
  final String city;
  final String zipcode;

  Address({this.street, this.suite, this.city, this.zipcode});

  factory Address.fromJson(Map<String, dynamic> addjson){

    return Address(
      street: addjson["street"],
      suite:  addjson["suite"],
      city: addjson["city"],
      zipcode: addjson["zipcode"]
    );
  }
}

This is the main.dart to read the json into the widget:

这是将 json 读入小部件的 main.dart:

import 'package:flutter/material.dart';
import 'model/users_future_model.dart';
import 'dart:convert';
import 'dart:async';
import 'package:http/http.dart' as http;

final String jsonplaceholder = "http://jsonplaceholder.typicode.com/users/";

//Future method to read the URL
Future<Users> fetchInfo() async{
  final response = await http.get(jsonplaceholder);
  final jsonresponse = json.decode(response.body);

  return Users.fromJson(jsonresponse);
}

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("Parse JSON"),
      ),
      body: new Center(
        child: new Column(
          children: <Widget>[
            new FutureBuilder(
                future: fetchInfo(),
                builder: (context, snapshot){
                  if(snapshot.hasData){
                    return new Text(snapshot.data.email);
                  }else if(snapshot.hasError){
                    return new Text("Error ${snapshot.error}");
                  }
                })
          ],
        ),
      )
    );
  }
}

This is the JSON information i'm trying to read although its only a small part of it:

这是我正在尝试阅读的 JSON 信息,尽管它只是其中的一小部分:

{
id: 1,
name: "Leanne Graham",
username: "Bret",
email: "[email protected]",
address: {
 street: "Kulas Light",
 suite: "Apt. 556",
 city: "Gwenborough",
 zipcode: "92998-3874",
 geo: {
  lat: "-37.3159",
  lng: "81.1496"
 }
},
phone: "1-770-736-8031 x56442",
website: "hildegard.org",
company: {
 name: "Romaguera-Crona",
 catchPhrase: "Multi-layered client-server neural-net",
 bs: "harness real-time e-markets"
}
}

The error i am currently running into is:

我目前遇到的错误是:

Error type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'

How do i rectify this error?

我如何纠正这个错误?

回答by Dhiraj Sharma

API returns JSON array not json object so that is List not Map.

API 返回 JSON 数组而不是 json 对象,因此是 List 而不是 Map。

i.e. User json is first element of Json Array.

即用户 json 是 Json 数组的第一个元素。

So to get first element use first index. Inside fetch Info update

所以要获取第一个元素,请使用第一个索引。内部获取信息更新

return Users.fromJson(jsonresponse[0]);

return Users.fromJson(jsonresponse[0]);

回答by kapsid

checkout the article by Pooja Bhaumik,

查看 Pooja Bhaumik 的文章,

Parsing complex Json in flutter

在颤动中解析复杂的 Json

The article simplifies Json parsing in flutter.

文章简化了flutter中的Json解析。