1

当我尝试解码 Json 响应时出现格式异常。请帮忙。未处理的异常:FormatException:意外字符(在字符 3 处)[{table_no: 1}, {table_no: 2}, {table_no: 3}]

[
    {
        "table_no": "1"
    },
    {
        "table_no": "2"
    },
    {
        "table_no": "3"
    }
]

Future<Response> pos_client_table() async {

  String url =
      'https://xxxxxx.com/api/v1/table?branch_id=1';
  Response response;
  Dio dio = new Dio();
  dio.options.headers = {'Authorization': prefs.getString('posclient_token')};

  try {
    response = await dio.get(url);

    var jso = json.decode(response.toString());

    Fluttertoast.showToast(
        msg: "$jso",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        timeInSecForIos: 1,
        backgroundColor: Colors.red,
        textColor: Colors.white,
        fontSize: 16.0);

  } catch (e) {
    print(e);
  }

  return response;
}

 void CallTableUrl() async {
    Response response = await pos_client_table();
    List<Map> _myJson = json.decode(response.toString());
    showInSnackBar('$_myJson');
  }
4

1 回答 1

0

编辑添加dio解析示例和解析图片

Response response;
Dio dio = new Dio();
response = await dio.get("http://yoursite");
print(response);
print(response.data.toString());

List<Payload> payload = payloadFromJson(response.data);
print({payload[0].tableNo});

假设 dio 已经返回正确的 json 字符串是

String jsonString = '[{"table_no": "1"},{"table_no": "2"},{"table_no": "3"}]';

第 1 步:使用有效负载类解析 jsonString

List<Payload> payload = payloadFromJson(jsonString);

有效载荷类

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

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

class Payload {
  String tableNo;

  Payload({
    this.tableNo,
  });

  factory Payload.fromJson(Map<String, dynamic> json) => Payload(
        tableNo: json["table_no"],
      );

  Map<String, dynamic> toJson() => {
        "table_no": tableNo,
      };
}

第 2 步:将此有效负载传输到所需的 DropdownMenuItem 映射

for (var i = 0; i < payload.length; i++) {
      _myJson.add({'id': payload[i].tableNo, 'name': payload[i].tableNo});
    }

第 3 步:填充 DropdownMenuItem

DropdownButton<String>(
                  isDense: true,
                  hint: Text("${payload[0].tableNo}"),
                  value: _mySelection,
                  onChanged: (String Value) {
                    setState(() {
                      _mySelection = Value;
                    });
                    print(_mySelection);
                  },
                  items: _myJson.map((Map map) {
                    return DropdownMenuItem<String>(
                      value: map["id"].toString(),
                      child: Text(
                        map["name"],
                      ),
                    );
                  }).toList(),
                ),

完整代码

import 'package:flutter/material.dart';
import 'dart:convert';

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

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

class Payload {
  String tableNo;

  Payload({
    this.tableNo,
  });

  factory Payload.fromJson(Map<String, dynamic> json) => Payload(
        tableNo: json["table_no"],
      );

  Map<String, dynamic> toJson() => {
        "table_no": tableNo,
      };
}

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

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

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

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

String jsonString = '[{"table_no": "1"},{"table_no": "2"},{"table_no": "3"}]';
List<Payload> payload = payloadFromJson(jsonString);

List<Map> _myJson = [];

class _MyHomePageState extends State<MyHomePage> {
  String _mySelection;

  @override
  void initState() {
    for (var i = 0; i < payload.length; i++) {
      _myJson.add({'id': payload[i].tableNo, 'name': payload[i].tableNo});
    }
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Column(
          children: <Widget>[
            Container(
              height: 500.0,
              child: Center(
                child: DropdownButton<String>(
                  isDense: true,
                  hint: Text("${payload[0].tableNo}"),
                  value: _mySelection,
                  onChanged: (String Value) {
                    setState(() {
                      _mySelection = Value;
                    });
                    print(_mySelection);
                  },
                  items: _myJson.map((Map map) {
                    return DropdownMenuItem<String>(
                      value: map["id"].toString(),
                      child: Text(
                        map["name"],
                      ),
                    );
                  }).toList(),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

在此处输入图像描述

在此处输入图像描述

于 2019-10-08T09:17:52.437 回答