【问题标题】:I need to solve FormatException: Unexpected character Flutter?我需要解决 FormatException: Unexpected character Flutter?
【发布时间】:2020-10-20 10:15:04
【问题描述】:

大家好,当我调用这个 json.decode(jsonString) 时,我得到了这个异常(意外字符),但有时当我运行应用程序时它不会抛出任何异常。 当出现此异常时,来自服务器的预期数据不会显示在应用程序上。 我在 localhost 中测试我的 API。 我的代码:

Future<List<Governorate>> getGovernorates() async {
    var governorates = List<Governorate>();
    var governorate = await client.get('$endpoint/governorates');
    String jsonString = governorate.body?.toString();
    if(governorate.statusCode == 200){
      //print("governorate =====> ${jsonString}");
      var parsed= json.decode(jsonString) as List<dynamic>; // sometimes it's fails here and throw the exeption FormatException: Unexpected character 
      for(var gov in parsed){
        governorates.add(Governorate.fromJson(gov));
      }
    } else {
      throw "Can't get governorates";
    }
    return governorates;
  }

json 对象:

[
    {
        "id": 1,
        "governorate_name": "test governorate",
        "governorate_cities": []
    },
 {
        "id": 1,
        "governorate_name": "test governorate 2",
        "governorate_cities": [
                              {
                "id": 11,
                "city_name": "test city",
                "governorate_id": 1
               
            }

]
    }
]

我试图解决这个问题,但我没有成功我希望你们给我关于这个问题的想法以及我该如何解决它 感谢您的关注。期待您的回答。

【问题讨论】:

  • 尝试解码为 Map
  • 我返回的响应不是 Map 的子类型
  • 你给我们看的jsonobject是flutter的print?或者它是实际的 jsonObject,因为如果是,它不应该包含值的尾随逗号
  • 因为根对象可能是一个数组
  • 将根对象分配给某个键,然后尝试将其解析为 Map

标签: flutter dart


【解决方案1】:

只需查看我根据您提供的 json 实现的代码即可。

这是您提供的 json。

[
    {
       "id":1,
       "governorate_name":"test governorate",
       "governorate_cities":[
 
       ]
    },
    {
       "id":1,
       "governorate_name":"test governorate 2",
       "governorate_cities":[
          {
             "id":11,
             "city_name":"test city",
             "governorate_id":1
          }
       ]
    }
 ]

从上面的 json 我已经为它创建了一个模型类,只需检查一下

// To parse this JSON data, do
//
//     final governorate = governorateFromJson(jsonString);

import 'dart:convert';

List<Governorate> governorateFromJson(String str) => List<Governorate>.from(json.decode(str).map((x) => Governorate.fromJson(x)));

String governorateToJson(List<Governorate> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Governorate {
    Governorate({
        this.id,
        this.governorateName,
        this.governorateCities,
    });

    int id;
    String governorateName;
    List<GovernorateCity> governorateCities;

    factory Governorate.fromJson(Map<String, dynamic> json) => Governorate(
        id: json["id"],
        governorateName: json["governorate_name"],
        governorateCities: List<GovernorateCity>.from(json["governorate_cities"].map((x) => GovernorateCity.fromJson(x))),
    );

    Map<String, dynamic> toJson() => {
        "id": id,
        "governorate_name": governorateName,
        "governorate_cities": List<dynamic>.from(governorateCities.map((x) => x.toJson())),
    };
}

class GovernorateCity {
    GovernorateCity({
        this.id,
        this.cityName,
        this.governorateId,
    });

    int id;
    String cityName;
    int governorateId;

    factory GovernorateCity.fromJson(Map<String, dynamic> json) => GovernorateCity(
        id: json["id"],
        cityName: json["city_name"],
        governorateId: json["governorate_id"],
    );

    Map<String, dynamic> toJson() => {
        "id": id,
        "city_name": cityName,
        "governorate_id": governorateId,
    };
}

这就是我在列表视图中为名称显示示例 ui 的地方。


import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:json_parsing_example/models.dart';



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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Users'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  bool _isLoading = false;
  List<Governorate> dataList = List();
  Future<String> loadFromAssets() async {
    return await rootBundle.loadString('json/parse.json');
  }

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

  getData() async {
    setState(() {
      _isLoading = true;
    });
    String jsonString = await loadFromAssets();
    final governorate = governorateFromJson(jsonString);

    dataList = governorate;

    setState(() {
      _isLoading = false;
    });
  }
/* 

// This will be in your case as per you code  
  Future<List<Governorate>> getGovernorates() async {
    var governorates = List<Governorate>();
    var governorate = await client.get('$endpoint/governorates');
    String jsonString = governorate.body?.toString();
    if(governorate.statusCode == 200){
     
    return governorateFromJson(jsonString);
    }
  } */

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: _isLoading
          ? Center(
              child: CircularProgressIndicator(),
            )
          : Container(
              child: ListView.builder(
                  itemCount: dataList.length,
                  shrinkWrap: true,
                  itemBuilder: (context, i) {
                    return Card(
                        child: Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Text(dataList[i].governorateName),
                    ));
                  }),
            ),
    );
  }
}





这可能是因为列表为空,只需检查以下代码并让我知道错误仍然发生

从模型类中更改以下工厂方法

factory NewMessagesModel.fromJson(Map<String, dynamic> json) => NewMessagesModel(
        id: json["id"],
        governorateName: json["governorate_name"],
        governorateCities: json["governorate_cities"] ==null ?null:List<GovernorateCity>.from(json["governorate_cities"].map((x) => GovernorateCity.fromJson(x))),
    );

    Map<String, dynamic> toJson() => {
        "id": id,
        "governorate_name": governorateName,
        "governorate_cities":json["governorate_cities"] ==null?null : List<dynamic>.from(governorateCities.map((x) => x.toJson())),
    };
}

只需检查注释代码,我已经带您获取 api 代码并进行了一些修改,以便它可以工作,并让我知道它是否工作。

【讨论】:

  • 谢谢兄弟,但有时也可以工作,有时我会遇到和以前一样的异常
  • 最后检查一下我添加了两个 json 的代码,你提供的 json 有一些关于 , 字符的问题,如果它被删除,它可能工作正常,只需与你的 api 开发人员核实 json 标准
  • 我在复制 json 的一部分时忘记删除的多余逗号,因为它是一个长的 json 对象。抱歉,我编辑了帖子
  • 您可以添加您收到的错误的完整日志吗?
  • codeshare.io/axXOlB 但我想知道为什么有时效果很好:|
猜你喜欢
  • 1970-01-01
  • 2021-10-02
  • 1970-01-01
  • 2020-08-26
  • 2020-09-12
  • 2021-06-17
  • 2019-10-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多