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);}}