zl程序教程

您现在的位置是:首页 >  其他

当前栏目

【Flutter】JSON 模型转换 ( JSON 序列化工具 | JSON 手动序列化 | 根据 JSON 编写 Dart 模型类 | 在线自动根据 JSON 转换 Dart 类 )

2023-06-13 09:17:55 时间

文章目录

一、JSON 序列化工具


JSON 格式比较简单的话 , 使用自带的 dart:convert 包 , 手动进行 JSON 的序列化与反序列化的操作即可 ;

/// json 序列化 , 反序列化 包
import 'dart:convert';

如果 JSON 格式很复杂 , 就需要使用 JSON 的序列化插件 ;

二、JSON 手动序列化


给定如下 JSON 字符串 :

{
  "icon": "icon.png",
  "title": "标题",
  "url": "https://www.baidu.com/",
  "statusBarColor": "FFFFFF",
  "hideAppBar": true
}

写成一行 :

{ "icon": "icon.png", "title": "标题", "url": "https://www.baidu.com/", "statusBarColor": "FFFFFF", "hideAppBar": true }

将上述 JSON 字符串序列化为 Map<String, dynamic> 格式的数据 ;

代码示例 :

import 'dart:convert';

void main() {
  String jsonString = '{ "icon": "icon.png", "title": "标题", "url": "https://www.baidu.com/", "statusBarColor": "FFFFFF", "hideAppBar": true }';

  /// 处理中文乱码
  Utf8Codec utf8codec = Utf8Codec();
  Utf8Decoder utf8decoder = Utf8Decoder();
  Utf8Encoder utf8encoder = Utf8Encoder();

  /// 将二进制 Byte 数据以 UTF-8 格式编码 , 获取编码后的字符串
  String responseString = utf8decoder.convert(utf8codec.encode(jsonString));

  // 将 json 字符串信息转为 Map<String, dynamic> 类型的键值对信息
  Map<String, dynamic> jsonMap = json.decode(responseString);

  // 使用工厂方法构造 Dart 对象
  CommonModel commonModel = CommonModel.fromJson(jsonMap);

  print('icon : ${commonModel.icon}\ntittle : ${commonModel.title}\nurl : ${commonModel.url}');
}

// Dart 模型类
class CommonModel {
  final String? icon;
  final String? title;
  final String? url;
  final String? statusBarColor;
  final bool? hideAppBar;

  CommonModel({this.icon, this.title, this.url, this.statusBarColor, this.hideAppBar});

  factory CommonModel.fromJson(Map<String, dynamic> json) {
    return CommonModel(
      icon: json['icon'],
      title: json['title'],
      url: json['url'],
      statusBarColor: json['statusBarColor'],
      hideAppBar: json['hideAppBar'],
    );
  }
}

执行结果 :

icon : icon.png
tittle : 标题
url : https://www.baidu.com/

三、根据 JSON 编写 Dart 模型类


给定一个指定格式的 JSON 类 , 将其转为 Dart , 如果进行手动转换 ,

{
  "school": "第一小学",
  "students": [
    {
      "name": "小王",
      "age": "12"
    },
    {
      "name": "小白",
      "age": "13"
    }
  ]
}

成员变量是普通变量的情况 : 没有使用 final 修饰 ;

class School {
  /// json 字符串中 school 字段
  String? school;

  /// json 字符串中的 students 数组
  List<Student>? students;

  School({this.school, this.students});

  /// 构造方法有两种写法
  /// 参数不是 final 类型的 , 就使用这种方式编写
  /// 方法前不需要添加 factory
  /// 如果成员是 final 类型的 , 那么方法前需要加入 factory
  School.fromJson(Map<String, dynamic> json) {
    school = json['school'];

    /// 先将 json 数组转为 List
    /// 然后调用 map 方法 , 为具体的每个元素赋值
    (json['students'] as List).map((i) => Student.fromJson(i));
  }
}

class Student {
  String? name;
  String? age;

  Student({this.name, this.age});

  Student.fromJson(Map<String, dynamic> json) {
    name = json['name'];
    age = json['age'];
  }
}

成员变量使用 final 修饰的情况 :

class School {
  /// json 字符串中 school 字段
  final String? school;

  /// json 字符串中的 students 数组
  final List<Student>? students;

  School({this.school, this.students});

  /// 构造方法有两种写法
  /// 参数不是 final 类型的 , 就使用这种方式编写
  /// 方法前不需要添加 factory
  /// 如果成员是 final 类型的 , 那么方法前需要加入 factory
  factory School.fromJson(Map<String, dynamic> json) {
    String school = json['school'];

    /// 先将 json 数组转为 List
    /// 然后调用 map 方法 获取每个值
    List<Student> students = (json['students'] as List).map((i) => Student.fromJson(i)).toList();

    return School(school: school, students: students);
  }
}

class Student {
  final String? name;
  final String? age;

  Student({this.name, this.age});

  factory Student.fromJson(Map<String, dynamic> json) {
    String name = json['name'];
    String age = json['age'];

    return Student(name: name, age: age);
  }
}

四、在线自动转换


除了转为 Dart 类型之外 , 其它 语言 类型 也可以转换 , https://www.bejson.com/json2javapojo/new/ 网站可以 JSON 转 JavaBean ;

推荐一个 JSON 转 Dart 的工具网站 : https://jsontodart.com/

这是系统根据 JSON 字符串自动生成的 Dart 类 ;

class Autogenerated {
  String school;
  List<Students> students;

  Autogenerated({this.school, this.students});

  Autogenerated.fromJson(Map<String, dynamic> json) {
    school = json['school'];
    if (json['students'] != null) {
      students = new List<Students>();
      json['students'].forEach((v) {
        students.add(new Students.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['school'] = this.school;
    if (this.students != null) {
      data['students'] = this.students.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class Students {
  String name;
  String age;

  Students({this.name, this.age});

  Students.fromJson(Map<String, dynamic> json) {
    name = json['name'];
    age = json['age'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['name'] = this.name;
    data['age'] = this.age;
    return data;
  }
}

五、相关资源


参考资料 :

重要的专题 :

博客源码下载 :

  • GitHub 地址 : https://github.com/han1202012/flutter_http( 随博客进度一直更新 , 有可能没有本博客的源码 )
  • 博客源码快照 : ( 本篇博客的源码快照 , 可以找到本博客的源码 )