[Journey] Flutter and Json serialization -Day9

dart: convert JSON serialization manual | library using the sequence of the code generation JSON

dart: convert manually serialized JSON

  • Source
import 'dart:convert';
//创建一个模型类
class Student{
  String name;
  int age;
  Student(this.name,this.age);
  //用于从一个map构造出一个Student实例
  Student.fromJson(Map<String,dynamic> json):
      name = json['name'],
      age = json['age'];
  // 将Student实例转化为一个map.
  //jsonDecode(jsonStr) 方法中会调用实体类的这个方法。如果实体类中没有这个方法,会报错。
  Map<String,dynamic> toJson(){
    return
        {
          "name": name,
          "age" : age
        };
  }
}
void main() {
  // 创建Json字符串(Json必须用双引号)
  String jsonfile = '{"name":"MJT","age" :19}';
  //用jsonDecode将Json解码为Map
  Map<String, dynamic> map = jsonDecode(jsonfile);
  //从map中构造出Student实例并使用
  Student student = Student.fromJson(map);
  print(student.name);
  //将实例对象编码为Json
  String temp = jsonEncode(student);
  print(temp);
}

Using the code generation library serialization JSON

Set in the project json_serializable

To include json_serializable to our project.
pubspec.yaml

dependencies:
  json_annotation: ^3.0.0

dev_dependencies:
  build_runner: ^1.0.0
  json_serializable: ^3.2.0

Run flutter packages get in the project root folder (or click "Packages Get" in the editor) to use these new dependencies in the project.

View the latest version of the required dependencies: https://github.com/dart-lang/json_serializable/blob/master/example/pubspec.yaml

Json_serializable way to create a model class

import 'package:json_annotation/json_annotation.dart';
// student.g.dart 将在我们运行生成命令后自动生成
import 'student.g.dart';
///这个标注是告诉生成器,这个类是需要生成Model类的
@JsonSerializable()

//下面的代码不变
class Student{
    ......
}
void main(){
    ......
}

Generate a one-time

Under the root directory of the project Flutter Packages Pub RUN build_runner Build , may generate json model serialization code when needed. But each time a change must be manually run again build commands, too inconvenient in the model class.

Continue to generate

watcher_ will monitor the project file changes and automatically build the necessary documents when needed.
Simply run in the root directory flutter packages pub run build_runner watch to start _watcher
.
Just start a viewer, and then let it run in the background.

Use json_serializable model

Used, without modifying the previous code after the code sequence generated directly run just fine.

Reference documents: https://flutterchina.club/json/

Published 47 original articles · won praise 5 · Views 2930

Guess you like

Origin blog.csdn.net/qq_15989473/article/details/104227682