无法将 json 响应转换为列表。铸造错误

Unable to convert json response to list. Casting error

我正在尝试将我的 json 响应转换为列表但出现以下错误。 Json 是在map里面抓取的,但是需要把map转成list显示在listview中。

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

Json 回应

{"78":{"id":118,"first_name":"test","last_name":null,"email":"jignesh.test@gmail.com","phone":"","city":"null","state":"null","countrie_id":1,"location":"null","lat":"37.421998333333335","lng":"-122.08400000000002","image":"","role_id":3,"client_id":3,"coordinator_id":1,"sst_id":2,"created_at":"2018-10-08 10:59:18","updated_at":"2018-10-08 10:59:18","deleted_at":null,"status":0},
"79":{"id":119,"first_name":"Rahul test","last_name":null,"email":"rahul.test@gmail.com","phone":"","city":"null","state":"null","countrie_id":1,"location":"null","lat":"19.2284","lng":"72.85813","image":"","role_id":3,"client_id":3,"coordinator_id":1,"sst_id":2,"created_at":"2018-10-08 11:19:14","updated_at":"2018-10-08 11:19:14","deleted_at":null,"status":0},
"80":{"id":120,"first_name":"Customer Name","last_name":null,"email":"jjkkk@gmail.com","phone":"","city":"Mumbai","state":"Maharastra","countrie_id":1,"location":"virar","lat":"123","lng":"456","image":"images\/customer_image\/0hUSFUSqYAQTt57bVnnHjuQUOACECWzBOfJLWWa6.png","role_id":3,"client_id":1,"coordinator_id":1,"sst_id":2,"created_at":"2018-10-09 12:24:08","updated_at":"2018-10-09 14:03:07","deleted_at":null,"status":0},"status":"success","message":"List Fetched Successfully."}

下面是我调用 post api 方法的 Future 方法。

 Future<PosModelData> posList(){
  print('pos list api called');
  return networkUtil.post("http://192.168.0.46/api/v1/poslist",body:{
      "sstId":"2"
  }).then((response){
    if(response["status"]=="success"){
      print("List fetched");
      posLists=((response) as List).map((data)=>new PosModelData.fromJson(data)).toList();
      // print(response.toString());
      // print(posLists);
    }
  });
}

PosModel.dart

    class PosModelData {
  final String first_name;
  final String last_name;
  final String email;

  PosModelData({this.first_name, this.last_name, this.email});

  factory PosModelData.fromJson(Map json) {
    return new PosModelData(
      first_name: json['first_name'],
      last_name: json['last_name'],
      email: json['email'],
    );
  }
}

NetworkUtil.dart

Future<dynamic> post(String url, {Map header, body, encoding}) {
return http
    .post(url, body: body, headers: header, encoding: encoding)
    .then((http.Response response) {
  final String resBody = response.body;

  return jsonDecoder.convert(resBody);
});
}

您假设您的 JSON 响应是对象列表,而实际上它是一个具有映射到 PosModelData.

键的对象

您应该将您的服务器响应更改为:

[
   {
      "id":118,
      "first_name":"test",
      "last_name":null,
      ...
   },
   {
      "id":119,
      "first_name":"Rahul test",
      "last_name":null,
      ...
   }
]

或更改您解析 JSON 响应的方式。

恐怕您的 json string/response 未正确创建。

在同一个地图中,您有状态,然后是列表的每个元素,因此无法提取列表。您可以重新格式化服务器响应,然后得到如下代码所示:

import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

String responseStr = '''
{
"status":"success",
"message":"List Fetched Successfully.",
"posts":
  [
    {"id":118,"first_name":"test","last_name":null,"email":"jignesh.test@gmail.com","phone":"","city":"null","state":"null","countrie_id":1,"location":"null","lat":"37.421998333333335","lng":"-122.08400000000002","image":"","role_id":3,"client_id":3,"coordinator_id":1,"sst_id":2,"created_at":"2018-10-08 10:59:18","updated_at":"2018-10-08 10:59:18","deleted_at":null,"status":0},
    {"id":119,"first_name":"Rahul test","last_name":null,"email":"rahul.test@gmail.com","phone":"","city":"null","state":"null","countrie_id":1,"location":"null","lat":"19.2284","lng":"72.85813","image":"","role_id":3,"client_id":3,"coordinator_id":1,"sst_id":2,"created_at":"2018-10-08 11:19:14","updated_at":"2018-10-08 11:19:14","deleted_at":null,"status":0},
    {"id":120,"first_name":"Customer Name","last_name":null,"email":"jjkkk@gmail.com","phone":"","city":"Mumbai","state":"Maharastra","countrie_id":1,"location":"virar","lat":"123","lng":"456","image":"images\/customer_image\/0hUSFUSqYAQTt57bVnnHjuQUOACECWzBOfJLWWa6.png","role_id":3,"client_id":1,"coordinator_id":1,"sst_id":2,"created_at":"2018-10-09 12:24:08","updated_at":"2018-10-09 14:03:07","deleted_at":null,"status":0}
  ]
}
''';

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

class MyHomePage extends StatefulWidget {

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<PosModelData> postList;

  @override
  void initState() {
    super.initState();
    getPosts();
  }

  Future<Null> getPosts() async {
    // Your http logic
    Map<String, dynamic> response = json.decode(responseStr);
    if (response["status"] == "success") {
      postList = ((response["posts"]) as List)
          .map((data) => new PosModelData.fromJson(data))
          .toList();
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(),
      body: Center(
        child: postList != null ?
        Column(
          children: <Widget>[
            new Text("${postList[0].first_name} ${postList[0].email}"),
            new Text("${postList[1].first_name} ${postList[1].email}"),
            new Text("${postList[2].first_name} ${postList[2].email}"),
          ],
        ) : CircularProgressIndicator(),
      ),
    );
  }
}

class PosModelData {
  final String first_name;
  final String last_name;
  final String email;

  PosModelData({this.first_name, this.last_name, this.email});

  factory PosModelData.fromJson(Map json) {
    return new PosModelData(
      first_name: json['first_name'],
      last_name: json['last_name'],
      email: json['email'],
    );
  }
}