DartVM服务器开发(二十一)-Dart中的Gson(jaguar_serializer)

今天我们来学习一下如何使用jaguar_serializer包,这里说明一下,该包在三端平台都是可用的(Flutter,dart web ,dart vm),学习过安卓的,都知道gson吧,该包类似于gson

1.引入包

1
2
3
4
5
6
7
#pubspec.yaml
dependencies:
jaguar_serializer: ^2.2.0

dev_dependencies:
build_runner:
jaguar_serializer_cli:

执行pub get命令
获取成功.png
导包

1
import 'package:jaguar_serializer/jaguar_serializer.dart';

2.初始化

  • 新增一个实体类

    1
    2
    3
    4
    class Person {
    String name;
    int age;
    }
  • 添加生成脚本标记

    1
    2
    3
    @GenSerializer()
    class PersonSerializer extends Serializer<Person> with _$PersonSerializer {
    }
  • 运行脚本
    使用脚本命令pub run build_runner build
    image.png

  • 导入生成代码
    回到person这个类的文件中,添加
    1
    part 'person.jser.dart';

## 3.使用

1
2
3
4
5
6
7
8
9
10
11
12
13
main() async {
Jaguar(port: 1000)
..get('/person', (ctx){
PersonSerializer personSerializer=new PersonSerializer();
Person person=new Person()
..name='rhyme'
..age=18;
//personSerializer.toMap(person)获取到map对象
return Response.json( personSerializer.toMap(person));
})
..log.onRecord.listen(print)
..serve(logRequests: true);
}

然后我们来请求一下
image.png
成功返回了json数据

4.使用详解

  • json与对象相互转换

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    import 'dart:convert';
    main(){
    String jsonString='{"name":"rhyme","age":18}';
    PersonSerializer personSerializer=new PersonSerializer();

    // json to entity
    Person person=personSerializer.fromMap(json.decode(jsonString));
    print('name:${person.name} ,age: ${person.age}');

    //entity to json
    String toJson= json.encode( personSerializer.toMap(person));
    print(toJson);
    }
  • json 与对象列相互转换

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    main(){
    String jsonString='[{"name":"rhyme","age":18},{"name":"ben","age":21}]';
    PersonSerializer personSerializer=new PersonSerializer();

    // list: json to entity
    //因为目前fromList不支持dynamic的值,所以,我们需要吧json.decode出来的List<dynamic>转化为List<Map>,不然会报异常
    List<Map> mapList=(json.decode(jsonString) as List<dynamic>).map((dy)=>dy as Map).toList();
    List<Person> persons=personSerializer.fromList(mapList);
    for(Person p in persons){
    print('name:${p.name} ,age: ${p.age}');
    }
    //list: entity to json
    String fromJson=json.encode(personSerializer.toList(persons));
    print(fromJson);
    }
  • 对象内嵌对象与json相互转换

    在对象内添加一个对象

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    class Person {
    String name;
    int age;
    //new
    Info info;
    //new
    }

    //new
    class Info{
    String address;
    String phoneNumber;
    }
    //edit
    @GenSerializer( serializers: [ InfoSerializer])
    //edit
    class PersonSerializer extends Serializer<Person> with _$PersonSerializer {
    }

    //new
    @GenSerializer()
    class InfoSerializer extends Serializer<Info> with _$InfoSerializer {
    }
    //new

运行命令pub run build_runner build
image.png
转换跟上面相同

1
2
3
4
5
6
7
8
9
10
String jsonString='{"name":"rhyme","age":18,"info":{"address":"广州","phoneNumber":"159xxxxxxxx"}}';
PersonSerializer personSerializer=new PersonSerializer();

// json to entity
Person person=personSerializer.fromMap(json.decode(jsonString));
print('name:${person.name} ,age: ${person.age}');

//entity to json
String toJson= json.encode(personSerializer.toMap(person));
print(toJson);

  • 对象内嵌对象列

    将上面的Info改为List<Info>
    重新运行命令pub run build_runner build
    转换跟上面一样

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    String jsonString='[{"name":"rhyme","age":18,"info":[{"address":"广州","phoneNumber":"159xxxxxxxx"},{"address":"北京","phoneNumber":"158xxxxxxxx"}]},{"name":"ben","age":21}]';
    PersonSerializer personSerializer=new PersonSerializer();

    // list: json to entity
    //因为目前fromList不支持dynamic的值,所以,我们需要吧json.decode出来的List<dynamic>转化为List<Map>,不然会报异常
    List<Map> mapList=(json.decode(jsonString) as List<dynamic>).map((dy)=>dy as Map).toList();
    List<Person> persons=personSerializer.fromList(mapList);
    for(Person p in persons){
    print('name:${p.name} ,age: ${p.age}');
    }
    //list: entity to json
    String fromJson=json.encode(personSerializer.toList(persons));
    print(fromJson);
  • 对象内嵌多个对象

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    class Person {
    String name;
    int age;
    List<Info> info;
    //new
    Avatar avatar;
    //new
    }


    class Info{
    String address;
    String phoneNumber;
    }
    //new
    class Avatar{
    String url;
    String path;

    }
    //new

    //edit
    @GenSerializer( serializers: [ InfoSerializer,AvatarSerializer])
    //edit
    class PersonSerializer extends Serializer<Person> with _$PersonSerializer {
    }

    @GenSerializer()
    class InfoSerializer extends Serializer<Info> with _$InfoSerializer {
    }
    //new
    @GenSerializer()
    class AvatarSerializer extends Serializer<Avatar> with _$AvatarSerializer {
    }
    //new

然后重新运行命令pub run build_runner build
使用也是跟上面相同

1
2
3
4
5
6
7
8
9
10
11
12
13
String jsonString='[{"name":"rhyme","age":18,"avatar":{"url":"http://www.baidu.com","path":"baidu"},"info":[{"address":"广州","phoneNumber":"159xxxxxxxx"},{"address":"北京","phoneNumber":"158xxxxxxxx"}]},{"name":"ben","age":21}]';
PersonSerializer personSerializer=new PersonSerializer();

// list: json to entity
//因为目前fromList不支持dynamic的值,所以,我们需要吧json.decode出来的List<dynamic>转化为List<Map>,不然会报异常
List<Map> mapList=(json.decode(jsonString) as List<dynamic>).map((dy)=>dy as Map).toList();
List<Person> persons=personSerializer.fromList(mapList);
for(Person p in persons){
print('name:${p.name} ,age: ${p.age}');
}
//list: entity to json
String fromJson=json.encode(personSerializer.toList(persons));
print(fromJson);

  • 别名

    有时候,我们的实体类成员变量名跟json数据中对应的字段不相同,可以使用@Alias('')对需要的字段进行标记,里面的值为json对应的字段
    1
    2
    3
    4
    5
    6
    7
    class Person {
    @Alias('Name')
    String name;
    int age;
    List<Info> info;
    Avatar avatar;
    }

要使上面生效,需要重新运行命令pub run build_runner build

  • Build命令

    我们可以发现,当我每次做一个修改,都需要执行pub run build_runner build命令,这样是非常容易导致疏忽的,jaguar_serializer已经为我们考虑到了,
    我们可以使用命令
    1
    pub run build_runner watch

当该命令运行后,我们的每次点击保存,都会重新激活一次脚本,如下图
image.png
如果你是Flutter开发,可以使用下面的build命令

1
flutter packages pub run build_runner build

Flutter的监听命令

1
flutter packages pub run build_runner watch

ok,今天就到这里了,我们明天见!

评论系统未开启,无法评论!