发生异常-JSON API错误-Flutter

时间:2019-09-30 08:25:21

标签: json flutter dart cross-platform

我需要将项目与JSON API连接,我遵循了flutter网站上的许多文档和堆栈溢出问题,但是遇到了很多问题,我编写了一些代码来与JSON连接,但是当我运行时使用Android SDK时出现此错误:

enter image description here

但是在AndroidMainifest.xml中添加了这一行之后:

<manifest xmlns:android="http://schemas.android.com/apk/res/android" <uses-permission android:name="android.permission.INTERNET" />

我在上面遇到了同样的错误!我确定我可以连接WiFi!

当我使用iOS SDK运行时,出现此错误:

enter image description here

代码:

import 'dart:convert';
import 'dart:async';
import 'package:http/http.dart' as http;
import 'package:flutter/foundation.dart';

List<Category> _catgList =new List<Category>();

Future<List<Category> > fetchCategory() async {
  final response = await http.get('url of json'); // Here first error

  if (response.statusCode == 200) {

    List<dynamic> values = new List<dynamic>();
    values = json.decode(response.body); // Here second error
    if(values.length>0){
      for(int i=0;i<values.length;i++){
        if(values[i]!=null){
          Map<String,dynamic> map=values[i];
          _catgList.add(Category.fromJson(map));
          debugPrint('Id-------${map['id']}');
          debugPrint('Id-------${map['title']}');
        }
      }
    }
    return _catgList;

  } else {
    throw Exception('Failed to load post');
  }
}

class Category {

  final int id;
  String title;


  Category({this.id, this.title});

  factory Category.fromJson(Map<String, dynamic> json) {
    return Category(
        id: json['id'],
        title: json['title'].toString(),
    );
  }
}

JSON:

{
    "status" : "ok",
    "count" : 14,
    "categories" : [
      {
        "id" : 2,
        "title" : "world"
      },
      {
        "id" : 13,
        "title" : "games"
      },
      {
        "id" : 54,
        "title" : "woman"
      },
      {
        "id" : 50,
        "title" : "health"
      },
      {
        "id" : 48,
        "title" : "kitchen"
      },
      {
        "id" : 4292,
        "title" : "applications"
      },
      {
        "post_count" : 51,
        "id" : 51,
        "title" : "culture"
      },
      {
        "id" : 49,
        "title" : "sport"
      },
      {
        "id" : 8,
        "title" : "travel"
      },
      {
        "id" : 53,
        "title" : "policy"
      },
      {
        "id" : 52,
        "title" : "cars"
      },
      {
        "id" : 20,
        "title" : "tech"
      },
      {
        "id" : 4293,
        "title" : "gharaeb"
      },
      {
        "id" : 18,
        "title" : "business"
      }
    ]
  }

我的代码有什么问题?

2 个答案:

答案 0 :(得分:1)

您错过了json.decode或encoding。

    import 'dart:convert'

请参考我的http请求代码。

try{
  var client = new http.Client();
  var url = "Your Url";
  var response = await client.get(url);
    if(response.statusCode == 200){
      var results = json.decode(response.body);
      if(results['status'] == 'ok'){
         //if your result have loop 
         for(var item in results['categories']){
          //enter your code
          print(item['id'] + ":" + item['title']);
         }
         //you can use this your response value
         print(results['your_key1']['your_key2']); 
      }                  
  }
}on Exception catch(err){
 print("Error: $err");
}

希望对您有所帮助。

答案 1 :(得分:1)

第一个错误可能是由于某些网络问题或设置问题所致。对于第二个问题,请在代码中替换此行

values = json.decode(response.body);

values = json.decode(response.body)["categories"];

从提供的JSON数据可以明显看出,json.decode方法返回一个映射,您可以通过json.decode(response.body)["categories"]获取类别列表。