当前位置: 首页 > news >正文

Flutter开发 json_serializable json数据解析

从服务器获取数据转成list,再转成string。
数据格式:

{"data": [{"random": "0","star": 10,"def": "抛弃,遗弃;中止;陷入,沉湎于","pron": " əˈbændən","wordAudio": "http://dict.youdao.com/dictvoice?audio=abandon","word": "abandon"},{"random": "1","star": 10,"def": "抛弃;放纵","pron": " əˈbændənmənt","wordAudio": "http://dict.youdao.com/dictvoice?audio=abandonment","word": "abandonment"},{"random": "2","star": 10,"def": "缩略词,缩写形式;缩略","pron": " əˌbriːviˈeɪʃn","wordAudio": "http://dict.youdao.com/dictvoice?audio=abbreviation","word": "abbreviation"},{"random": "3","star": 10,"def": "中止,停顿;归属待定,暂搁","pron": " əˈbeɪəns","wordAudio": "http://dict.youdao.com/dictvoice?audio=abeyance","word": "abeyance"}]
}

添加依赖

dev_dependencies:json_serializable: ^6.10.0dependencies:json_annotation: ^4.9.0

创建类word.dart,添加JsonSerializable注释,添加part。

import 'package:json_annotation/json_annotation.dart';
part 'word.g.dart';()
class Word{Word();late String random;late int star;late String def;late String pron;late String wordAudio;late String word;String toString() {return 'Word{random: $random, star: $star, def: $def, pron: $pron, wordAudio: $wordAudio, word: $word}';}// 从JSON反序列化的工厂方法factory Word.fromJson(Map<String, dynamic> json) => _$WordFromJson(json);// 转换为JSON的方法Map<String, dynamic> toJson() => _$WordToJson(this);
}

在Termial中,输入dart run build_runner build。等待一会,会生成word.g.dart。

// GENERATED CODE - DO NOT MODIFY BY HANDpart of 'word.dart';// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************Word _$WordFromJson(Map<String, dynamic> json) => Word()..random = json['random'] as String..star = json['star'] as int..def = json['def'] as String..pron = json['pron'] as String..wordAudio = json['wordAudio'] as String..word = json['word'] as String;Map<String, dynamic> _$WordToJson(Word instance) => <String, dynamic>{'random': instance.random,'star': instance.star,'def': instance.def,'pron': instance.pron,'wordAudio': instance.wordAudio,'word': instance.word,
};

在word.dart中添加代码

import 'package:json_annotation/json_annotation.dart';
part 'word.g.dart';()
class Word{.....// 从JSON反序列化的工厂方法factory Word.fromJson(Map<String, dynamic> json) => _$WordFromJson(json);// 转换为JSON的方法Map<String, dynamic> toJson() => _$WordToJson(this);
}

接收数据,转换数据

  void httpGet() async {String url ="https://7a6396f8-09a1-4ade-b42a-f6db7776fb31.mock.pstmn.io/flutter";var result = await http.get(Uri.parse(url));if (result.statusCode == HttpStatus.ok) {print(result.body.length);//string转List<Word>List datas = jsonDecode(result.body)["data"];List<Word> wordList = List<Word>.from(datas.map((e) {return Word.fromJson(e);}),);for (var element in wordList) {print(element);}//list转stringString str = jsonEncode(wordList.map((e) {return e.toJson();}).toList(),);print(str);//或者直接使用jsonEncode//String str2 = jsonEncode(wordList);//print(str2);}}
I/flutter (22778): Word{random: 0, star: 10, def: 抛弃,遗弃;中止;陷入,沉湎于, pron:  əˈbændən, wordAudio: http://dict.youdao.com/dictvoice?audio=abandon, word: abandon}
I/flutter (22778): Word{random: 1, star: 10, def: 抛弃;放纵, pron:  əˈbændənmənt, wordAudio: http://dict.youdao.com/dictvoice?audio=abandonment, word: abandonment}
I/flutter (22778): Word{random: 2, star: 10, def: 缩略词,缩写形式;缩略, pron:  əˌbriːviˈeɪʃn, wordAudio: http://dict.youdao.com/dictvoice?audio=abbreviation, word: abbreviation}
I/flutter (22778): Word{random: 3, star: 10, def: 中止,停顿;归属待定,暂搁, pron:  əˈbeɪəns, wordAudio: http://dict.youdao.com/dictvoice?audio=abeyance, word: abeyance}I/flutter (22778): [{"random":"0","star":10,"def":"抛弃,遗弃;中止;陷入,沉湎于","pron":" əˈbændən","wordAudio":"http://dict.youdao.com/dictvoice?audio=abandon","word":"abandon"},{"random":"1","star":10,"def":"抛弃;放纵","pron":" əˈbændənmənt","wordAudio":"http://dict.youdao.com/dictvoice?audio=abandonment","word":"abandonment"},{"random":"2","star":10,"def":"缩略词,缩写形式;缩略","pron":" əˌbriːviˈeɪʃn","wordAudio":"http://dict.youdao.com/dictvoice?audio=abbreviation","word":"abbreviation"},{"random":"3","star":10,"def":"中止,停顿;归属待定,暂搁","pron":" əˈbeɪəns","wordAudio":"http://dict.youdao.com/dictvoice?audio=abeyance","word":"abeyance"}]

下面,再用quicktype生成下类来解析数据。

https://app.quicktype.io/
请添加图片描述

生成的类WordData

import 'dart:convert';WordData wordDataFromJson(String str) => WordData.fromJson(json.decode(str));String wordDataToJson(WordData data) => json.encode(data.toJson());class WordData {List<Datum> data;WordData({required this.data,});factory WordData.fromJson(Map<String, dynamic> json) => WordData(data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),);Map<String, dynamic> toJson() => {"data": List<dynamic>.from(data.map((x) => x.toJson())),};
}class Datum {String random;int star;String def;String pron;String wordAudio;String word;Datum({required this.random,required this.star,required this.def,required this.pron,required this.wordAudio,required this.word,});factory Datum.fromJson(Map<String, dynamic> json) => Datum(random: json["random"],star: json["star"],def: json["def"],pron: json["pron"],wordAudio: json["wordAudio"],word: json["word"],);Map<String, dynamic> toJson() => {"random": random,"star": star,"def": def,"pron": pron,"wordAudio": wordAudio,"word": word,};String toString() {return 'Datum{random: $random, star: $star, def: $def, pron: $pron, wordAudio: $wordAudio, word: $word}';}
}
  void httpGet() async {String url ="https://7a6396f8-09a1-4ade-b42a-f6db7776fb31.mock.pstmn.io/flutter";var result = await http.get(Uri.parse(url));if (result.statusCode == HttpStatus.ok) {print(result.body.length);WordData wd=  wordDataFromJson(result.body);print(wd.data);}}
http://www.dtcms.com/a/340366.html

相关文章:

  • 关联规则挖掘2:FP-growth算法(Frequent Pattern Growth,频繁模式增长)
  • rsync + inotify 数据实时同步
  • Android 入门到实战(三):ViewPager及ViewPager2多页面布局
  • 性能测试报告深度解析:从冰冷数据到火热洞察
  • android kernel代码 common-android13-5.15 下载 编译
  • Linux系统:C语言进程间通信信号(Signal)
  • RK3576赋能无人机巡检:多路视频+AI识别引领智能化变革
  • deque的原理与实现(了解即可)
  • 基于截止至 2025 年 6 月 4 日,在 App Store 上进行交易的设备数据统计,iOS/iPadOS 各版本在所有设备中所占比例详情
  • 比剪映更轻量!SolveigMM 视频无损剪切实战体验
  • shell变量进阶
  • 基于51单片机自动浇花1602液晶显示设计
  • Ubuntu-安装Epics Archiver Appliance教程
  • 玳瑁的嵌入式日记D21-08020(数据结构)
  • 服务器内存条不识别及服务器内存位置图
  • 认识Node.js及其与 Nginx 前端项目区别
  • 动手学深度学习(pytorch版):第五章节—多层感知机(1)层和块
  • 从异构计算视角审视ARM与FPGA:架构融合驱动智能时代计算范式革新
  • mybatis xml中表名 字段报红解决
  • S32K328(Arm Cortex-M7)适配CmBacktrace错误追踪
  • 生产电路板的公司有哪些?国内生产电路板的公司
  • 05-网关服务开发指南
  • 从零实现自定义顺序表:万字详解 + 完整源码 + 图文分析
  • 虚幻引擎目录结构
  • MYSQL-增删查改CRUD
  • Protobuf
  • AIStarter服务器版深度解析:与桌面版对比,解锁云端AI开发新体
  • STM32F4 外扩SRAM介绍及应用
  • word——如何给封面、目录、摘要、正文设置不同的页码
  • Web网站的运行原理1