无法将json响应转换为列表。投放错误

时间:2018-10-12 09:16:47

标签: api dart flutter dart-pub flutter-dependencies

我正在尝试将json响应转换为list,但出现以下错误。 Json是在地图内部获取的,但需要将地图转换为列表并显示在列表视图中。

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

Json Response

{"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);
});
}

2 个答案:

答案 0 :(得分:0)

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

您应该将服务器响应更改为以下内容:

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

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

答案 1 :(得分:0)

恐怕您的json字符串/响应未正确创建。

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

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'],
    );
  }
}