flutter json_annotation和json_serializable处理json数据序列化

flutter json_annotation和json_serializable处理json数据序列化

  • 导包

dependencies:
  json_annotation: ^2.4.0
 
dev_dependencies:
  fluttertoast: ^2.0.3
  json_serializable: ^3.0.0
  build_runner: ^1.6.0
  • 创建Author实体类(举例子,新建文件author.dart)

  • author.dart

import 'package:json_annotation/json_annotation.dart';

part 'author.g.dart';

@JsonSerializable() //注解
class Author {
    String name;
    String title;
    int id;
    Author({this.name, this.title, this.id});

    factory Author.fromJson(Map<String, dynamic> json) => _$AuthorFromJson(json);

    Map<String, dynamic> toJson(Author instance) => _$AuthorToJson(instance);
}

效果图:

 

这里有几点需要注意的

1、当我们初次创建Author.dart的时候,需要加入    part 'Author.g.dart';  虽然系统会提示报错,但是不必紧张,这个我们一会生成Author.g.dart文件所必须的条件,我们暂时不要管它报不报错

2、在需要转换的实体dart类前 加入@JsonSerializable()注解,表示需要json序列话处理

3、fromJson()  方法和 toJson()方法的写法是固定模式的,大家按模板修改就行

接下来我们就该见证奇迹的发生了

我们cd到项目的根目录,然后使用  flutter packages pub run build_runner build  这条指令去生成Author.g.dart文件

修改图如下:

然后我们就会在Author.dart的下面发现一个Author.g.dart文件,到此结束,我们开始验证是否有效

  • 编写测试类

import 'package:flutter/material.dart';
import '../model/author.dart';


class NoticePage extends StatefulWidget{
    @override
    _NoticePageState createState() => _NoticePageState();
}

class _NoticePageState extends State<NoticePage>{
    void _getData() async {
        var obj = {"name":"whisky", "title":'阿发生的发生阿斯蒂芬暗示法按时', "id":2020};
        var c = Author.fromJson(obj);
        print("作者的名字是:"+c.name);
        print("作者的名字是:"+c.title);
        print('${c.id}');
        print('${c.id.runtimeType}');
        print(c);
    }

    @override
    void initState(){
        super.initState();
        _getData();
    }

    @override
    Widget build(BuildContext context){
        final _main = Container(
            width: MediaQuery.of(context).size.width,
            padding: EdgeInsets.all(30),
            child: Column(
                children: [
                    Text('notice')
                ],
            ),
        );
        return Scaffold(
            appBar: AppBar(
                centerTitle: true,
                title: Text('我的消息',style: TextStyle(color: Colors.white)),
            ),
            body: _main,
        );
    }
}

打印结果:

 

 

测试完成,谢谢大家!!!

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章