Flutter中数Json序列化
Posted 夜辉疾风
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Flutter中数Json序列化相关的知识,希望对你有一定的参考价值。
pubspec.yaml
在pubspec.yaml中引入json序列化依赖
Dart的依赖仓库:https://pub.dev/
dependencies:
# json序列化
json_annotation: ^3.0.1
dev_dependencies:
# json序列化
build_runner: ^1.10.0
json_serializable: ^3.4.1
json_annotation.dart
import 'package:json_annotation/json_annotation.dart';//使用json_annotation序列化实体类
@JsonSerializable()//序列化的类添加该注解表示需要序列化
class Posts
int userId;
int id;
String title;
String body;
build model
使用flutter sdk 构建代码
flutter packages pub run build_runner build //一次性构建代码
flutter packages pub run build_runner watch //自动构建代码
自动生成Posts.dart类对应的Posts.g.dart文件
import 'package:json_annotation/json_annotation.dart';
part 'Posts.g.dart';
//这个标注是告诉生成器,这个类是需要生成Model类的
// flutter packages pub run build_runner build ;build 一次性构建代码
// flutter packages pub run build_runner watch 自动构建代码
@JsonSerializable()
class Posts
int userId;
int id;
String title;
String body;
Posts(this.userId, this.id, this.title, this.body);
//不同的类使用不同的mixin即可
factory Posts.fromJson(Map<String, dynamic> json) => _$PostsFromJson(json);
Map<String, dynamic> toJson() => _$PostsToJson(this);
使用
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:http/http.dart';
import 'bean/Posts.dart';
//异步任务
void main()
debugPaintSizeEnabled = false; //开启断点调试模式
runApp(_MyApp());
class _MyApp extends StatelessWidget
@override
Widget build(BuildContext context)
return MaterialApp(
title: 'Json',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: _MyHome(),
);
class _MyHome extends StatefulWidget
@override
State<StatefulWidget> createState()
return _LoadDataSate();
class _LoadDataSate extends State<_MyHome>
List<dynamic> widgets = []; //请求的数据
@override
void initState()
// TODO: implement initState
super.initState();
loadData();
//一个异步任务
Future<void> loadData() async
String dataURL = "https://jsonplaceholder.typicode.com/posts";
Response response = await get(dataURL);
setState(()
widgets = json.decode(response.body);
);
@override
Widget build(BuildContext context)
return Scaffold(
appBar: AppBar(
title: Text("JsonDecode"),
),
body: ListView.builder(
itemCount: widgets.length,
itemBuilder: (BuildContext context, int position)
return getRow(position);
,
),
);
//获得一个item
Widget getRow(int i)
var user = Posts.fromJson(widgets[i]);
return Padding(
padding: EdgeInsets.all(10.0),
child: Column(
children: <Widget>[
Text(" $user.userId"),
Text(" $user.id"),
Text(" $user.body"),
],
),
);
以上是关于Flutter中数Json序列化的主要内容,如果未能解决你的问题,请参考以下文章