当前位置:网站首页>[fluent] JSON model conversion (JSON serialization tool | JSON manual serialization | writing dart model classes according to JSON | online automatic conversion of dart classes according to JSON)
[fluent] JSON model conversion (JSON serialization tool | JSON manual serialization | writing dart model classes according to JSON | online automatic conversion of dart classes according to JSON)
2022-07-03 02:28:00 【Programmer community】
List of articles
- One 、JSON Serialization tool
- Two 、JSON Manual serialization
- 3、 ... and 、 according to JSON To write Dart Model class
- Four 、 Online automatic conversion
- 5、 ... and 、 Related resources
One 、JSON Serialization tool
JSON If the format is relatively simple , Use native dart:convert package , Manually JSON Serialization and deserialization of ;
/// json serialize , Deserialization package import 'dart:convert';
If JSON The format is complex , You need to use JSON The serialization plug-in for ;
- json_serializable : https://pub.dev/packages/json_serializable
- built_value : https://pub.dev/packages/built_value
Two 、JSON Manual serialization
Given as follows JSON character string :
{ "icon": "icon.png", "title": " title ", "url": "https://www.baidu.com/", "statusBarColor": "FFFFFF", "hideAppBar": true}
Write in a line :
{ "icon": "icon.png", "title": " title ", "url": "https://www.baidu.com/", "statusBarColor": "FFFFFF", "hideAppBar": true }
Put the above JSON String serialized to Map<String, dynamic> Formatted data ;
Code example :
import 'dart:convert';void main() {
String jsonString = '{ "icon": "icon.png", "title": " title ", "url": "https://www.baidu.com/", "statusBarColor": "FFFFFF", "hideAppBar": true }'; /// Deal with Chinese code Utf8Codec utf8codec = Utf8Codec(); Utf8Decoder utf8decoder = Utf8Decoder(); Utf8Encoder utf8encoder = Utf8Encoder(); /// Binary Byte The data to UTF-8 Format encoding , Get the encoded string String responseString = utf8decoder.convert(utf8codec.encode(jsonString)); // take json The string information is converted to Map<String, dynamic> Key value pair information of type Map<String, dynamic> jsonMap = json.decode(responseString); // Use the factory method to construct Dart object CommonModel commonModel = CommonModel.fromJson(jsonMap); print('icon : ${commonModel.icon}\ntittle : ${commonModel.title}\nurl : ${commonModel.url}');}// Dart Model class 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'], ); }}
Execution results :
icon : icon.pngtittle : title url : https://www.baidu.com/
3、 ... and 、 according to JSON To write Dart Model class
Given a specified format JSON class , Turn it into Dart , In case of manual conversion ,
{
"school": " The first primary school ", "students": [ {
"name": " Xiao Wang ", "age": "12" }, {
"name": " The small white ", "age": "13" } ]}
Member variables are ordinary variables : Not used final modification ;
class School {
/// json In a string school Field String? school; /// json In the string students Array List<Student>? students; School({
this.school, this.students}); /// There are two ways to construct /// The parameter is not final Type of , Write in this way /// There is no need to add factory /// If the member is final Type of , Then the method needs to be added factory School.fromJson(Map<String, dynamic> json) {
school = json['school']; /// First the json Array to List /// And then call map Method , Assign a value to each specific element (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']; }}
Member variables use final The condition of embellishment :
class School {
/// json In a string school Field final String? school; /// json In the string students Array final List<Student>? students; School({
this.school, this.students}); /// There are two ways to construct /// The parameter is not final Type of , Write in this way /// There is no need to add factory /// If the member is final Type of , Then the method needs to be added factory factory School.fromJson(Map<String, dynamic> json) {
String school = json['school']; /// First the json Array to List /// And then call map Method Get each value 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); }}
Four 、 Online automatic conversion
In addition to turning into Dart Out of type , Other Language type You can also convert , https://www.bejson.com/json2javapojo/new/ Website can JSON turn JavaBean ;
Recommend a JSON turn Dart The tools website : https://jsontodart.com/
This is the basis of the system JSON String is automatically generated Dart class ;
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; }}
5、 ... and 、 Related resources
Reference material :
- Flutter Official website : https://flutter.dev/
- Flutter Plug in download address : https://pub.dev/packages
- Flutter Developing documents : https://flutter.cn/docs ( Strongly recommend )
- official GitHub Address : https://github.com/flutter
- Flutter The Chinese community : https://flutter.cn/
- Flutter Practical tutorial : https://flutter.cn/docs/cookbook
- Flutter CodeLab : https://codelabs.flutter-io.cn/
- Dart Chinese document : https://dart.cn/
- Dart Developer website : https://api.dart.dev/
- Flutter Chinese net : https://flutterchina.club/ , http://flutter.axuer.com/docs/
- Flutter Related issues : https://flutterchina.club/faq/ ( It is recommended to watch it at the introductory stage )
- GitHub Upper Flutter Open source examples : https://download.csdn.net/download/han1202012/15989510
- Flutter Practical e-books : https://book.flutterchina.club/chapter1/
- Dart Language practice website : https://dartpad.dartlang.org/
Important topics :
- Flutter Animation reference documentation : https://flutterchina.club/animations/
Blog source download :
GitHub Address : https://github.com/han1202012/flutter_http( Keep updating with the progress of the blog , There may not be the source code of this blog )
Blog source snapshot : ( The source code snapshot of this blog , You can find the source code of this blog )
边栏推荐
- GBase 8c系统表-pg_class
- MUX VLAN Foundation
- The use of Flink CDC mongodb and the implementation of Flink SQL parsing complex nested JSON data in monggo
- 基于线程池的生产者消费者模型(含阻塞队列)
- The data in servlet is transferred to JSP page, and the problem cannot be displayed using El expression ${}
- Principle and application of database
- easyPOI
- Startup mode and scope builder of collaboration in kotlin
- easyExcel
- Pytorch convolution network regularization dropblock
猜你喜欢
[shutter] pull the navigation bar sideways (drawer component | pageview component)
【翻译】后台项目加入了CNCF孵化器
Y54. Chapter III kubernetes from introduction to mastery -- ingress (27)
Detailed introduction to the usage of Nacos configuration center
Solution for processing overtime orders (Overtime unpaid)
Coroutinecontext in kotlin
Producer consumer model based on thread pool (including blocking queue)
Create + register sub apps_ Define routes, global routes and sub routes
通达OA v12流程中心
Return a tree structure data
随机推荐
机器学习流程与方法
Su Shimin: 25 principles of work and life
GBase 8c系统表-pg_authid
awk从入门到入土(2)认识awk内置变量和变量的使用
Cancellation of collaboration in kotlin, side effects of cancellation and overtime tasks
iptables 4层转发
stm32F407-------DMA
Gbase 8C function / stored procedure parameters (II)
为什么会选择框架?选择什么样的框架
Machine learning process and method
Restcloud ETL cross database data aggregation operation
udp接收队列以及多次初始化的测试
require. context
random shuffle注意
Codeforces Round #418 (Div. 2) D. An overnight dance in discotheque
Servlet中数据传到JSP页面使用el表达式${}无法显示问题
4. Classes and objects
The use of Flink CDC mongodb and the implementation of Flink SQL parsing complex nested JSON data in monggo
Detailed analysis of micro service component sentinel (hystrix)
[codeforces] cf1338a - Powered addition [binary]