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

我为用户创建了一个模型类(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:

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:

{
id: 1,
name: "Leanne Graham",
username: "Bret",
email: "Sincere@april.biz",
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?

推荐答案

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

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

所以要获得第一个元素,请使用第一个索引.

return Users.fromJson(jsonresponse[0]);

Json相关问答推荐

如何在对象投影(*)上应用滤镜投影([?port==`eth1`])?

将 json 转换为 jsonb 安全吗?

Spark-SQL中的from_unixtime函数未能给出正确的输出

Powershell - 如何从 JSON 中删除/过滤元素但保留其余部分?

为什么根据其他工具,来自 aws rds 的 JSON 在 Docker 中格式错误运行?

如何在 wso2 中组合 2 个 json 有效负载?

使用 jq 获取特定键的所有父键

如何使用 boost::json::value 调用无参数函数

在 json 嵌入的 YAML 文件中 - 使用 Python 仅替换 json 值

单元测试球衣 Restful Services

JSON RPC - 什么是id?

如何使用 json.net 将数据表转换为 json 字符串?

按 JSON 数据类型 postgres 排序

谷歌浏览器不允许我放置断点

Jackson Scala 模块的小例子?

Rails 中奇怪的 JSON Javascript 问题

将 CoffeeScript 项目转换为 JavaScript(不缩小)?

json_encode() 返回 false

IE10/11 Ajax XHR 错误 - SCRIPT7002:XMLHttpRequest:网络错误 0x2ef3

如何在本地存储中存储对象数组?