【问题标题】:How to add utf8 decoder to solve the problem of Garbled characters in flutter http request?如何添加utf8解码器解决flutter http请求出现乱码问题?
【发布时间】:2020-08-13 05:44:00
【问题描述】:

我使用这个拓扑模型来解析 Json 数据。当我收到汉字时,数据变得乱码。

我尝试添加 utf8.decode 之类的

List<Client> clientFromJson(String str) => List<Client>.from(json.decode(utf8.decode(str)).map((x) => Client.fromJson(x)));

但 IDE 告诉我“参数类型 'String' 不能分配给参数类型 'List'”。

如何在模型中添加utf8解码器?

///topology.dart

// To parse this JSON data, do
//
//     final client = clientFromJson(jsonString);
//     final topology = topologyFromJson(jsonString);

import 'dart:convert';

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

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

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

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

class Topology {
  String location;
  String mode;
  String macAddress;
  String ipAddress;
  String downloadSpeed;
  String downloadSpeedUnit;
  String uploadSpeed;
  String uploadSpeedUnit;
  List<Client> client;

  Topology({
    this.location,
    this.mode,
    this.macAddress,
    this.ipAddress,
    this.downloadSpeed,
    this.downloadSpeedUnit,
    this.uploadSpeed,
    this.uploadSpeedUnit,
    this.client,
  });

  factory Topology.fromJson(Map<String, dynamic> json) => Topology(
    location: json["location"],
    mode: json["mode"],
    macAddress: json["macAddress"],
    ipAddress: json["ipAddress"],
    downloadSpeed: json["downloadSpeed"],
    downloadSpeedUnit: json["downloadSpeedUnit"],
    uploadSpeed: json["uploadSpeed"],
    uploadSpeedUnit: json["uploadSpeedUnit"],
    client: List<Client>.from(json["client"].map((x) => Client.fromJson(x))),
  );

  Map<String, dynamic> toJson() => {
    "location": location,
    "mode": mode,
    "macAddress": macAddress,
    "ipAddress": ipAddress,
    "downloadSpeed": downloadSpeed,
    "downloadSpeedUnit": downloadSpeedUnit,
    "uploadSpeed": uploadSpeed,
    "uploadSpeedUnit": uploadSpeedUnit,
    "client": List<dynamic>.from(client.map((x) => x.toJson())),
  };
}

class Client {
  String hostname;
  String macAddress;
  String ipAddress;
  String deviceType;
  String connectedNebula;
  String connectionType;
  String connectTime;

  Client({
    this.hostname,
    this.macAddress,
    this.ipAddress,
    this.deviceType,
    this.connectedNebula,
    this.connectionType,
    this.connectTime,
  });

  factory Client.fromJson(Map<String, dynamic> json) => Client(
    hostname: json["hostname"],
    macAddress: json["macAddress"],
    ipAddress: json["ipAddress"],
    deviceType: json["deviceType"],
    connectedNebula: json["connectedNebula"],
    connectionType: json["connectionType"],
    connectTime: json["connectTime"],
  );

  Map<String, dynamic> toJson() => {
    "hostname": hostname,
    "macAddress": macAddress,
    "ipAddress": ipAddress,
    "deviceType": deviceType,
    "connectedNebula": connectedNebula,
    "connectionType": connectionType,
    "connectTime": connectTime,
  };
}

//main.dart

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

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

class MyApp extends StatelessWidget {

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {

    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
    ]); 
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Topology',
      theme: ThemeData(),
      home: Home(),
    );
  }
}

class Home extends StatefulWidget {
  final String title;

  const Home({Key key, this.title}) : super(key: key);

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

class _HomeState extends State<Home> {
  var topologies = const [];

  Future loadTopologyList() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String managementPassword = prefs.getString("management_password");
    String username = 'admin';
    String basicAuth =
        'Basic ' + base64Encode(utf8.encode('$username:$managementPassword'));
    final String url ="some url";
    bool trustSelfSigned = true;
    HttpClient httpClient = HttpClient()
      ..badCertificateCallback =
      ((X509Certificate cert, String host, int port) => trustSelfSigned);
    IOClient ioClient = IOClient(httpClient);

    final response = await ioClient.get(url,
      headers: <String, String>{'authorization': basicAuth},
    );
    ioClient.close();
    String content = response.body;
    setState(() {
      topologies = topologyFromJson(content);
    });
  }

  void initState() {
    loadTopologyList();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xFFFAFAFA),
      appBar: AppBar(),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.fromLTRB(17, 0, 0, 0),
            child: Text('Topology'),
          ),
          Expanded(
            child: ListView.separated(
              itemCount: topologies.length,
              separatorBuilder: (context, index) => Divider(),
              itemBuilder: (BuildContext context, int index) {
                Topology topology = topologies[index]; 

                return ListTile(
                  title: Text(
                    topology.location,
                  ),
                  leading: CircleAvatar(
                      child: Image.asset(
                          "assets/drawable-mdpi/app_icon_circle.png")),
                  onTap: () {
                  },
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}

【问题讨论】:

    标签: json flutter dart https utf-8


    【解决方案1】:

    使用utf8.decode时必须传递response.bodyBytes

    例如:

    json.decode(utf8.decode(response.bodyBytes))
    

    如果你有一个字符串,那么你可以使用下面的代码来解码。

    utf8.decode(someString.runes.toList()),
    

    【讨论】:

    • runes.toList() 是关键!!谢谢
    【解决方案2】:

    我收到了这个错误: 未处理的异常:“List”类型不是“String”类型的子类型

    我在修改 topology.dart 时遇到了这个错误

    List<Client> clientFromJson(String str) => List<Client>.from(json.decode(utf8.decode(str.runes.toList())).map((x) => Client.fromJson(x)));
    
    String clientToJson(List<Client> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
    
    List<Topology> topologyFromJson(String str) => List<Topology>.from(json.decode(utf8.decode(str.runes.toList())).map((x) => Topology.fromJson(x)));
    
    String topologyToJson(List<Topology> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
    

    在 main.dart 中

    final json = jsonDecode(utf8.decode(response.bodyBytes));
        setState(() {
          topologies = topologyFromJson(json);
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-25
      • 1970-01-01
      • 1970-01-01
      • 2013-06-17
      • 1970-01-01
      • 2020-11-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多