zwvista

导航

使用 Dart 调用 REST API

JSON : Placeholder

JSON : Placeholder (https://jsonplaceholder.typicode.com/) 是一个用于测试的 REST API 网站。
以下使用 Dart 调用该网站的 REST API,获取字符串以及 JSON 数据。

  • GET /posts/1
  • GET /posts
  • POST /posts
  • PUT /posts/1
  • DELETE /posts/1

所有 GET API 都返回JSON数据,格式(JSON-Schema)如下:

{
  "type":"object",
  "properties": {
    "userId": {"type" : "integer"},
    "id": {"type" : "integer"},
    "title": {"type" : "string"},
    "body": {"type" : "string"}
  }
}

创建工程

打开 Intellij IDEA, 安装 Dart 插件
新建工程,选择 Dart -> Dart Command Line App, 输入 Dart SDK 路径,
然后点击 Next,输入工程名 example,完成向导。

添加依赖

在 pubspec.yaml 的 dependencies 部分添加依赖

dependencies:
  json_annotation: ^3.0.0
  analyzer: '0.39.14'
  http: 0.12.2

点击文件上方的 Pub get 链接下载依赖

Dart

example.dart 代码如下

import 'dart:convert';

import 'package:json_annotation/json_annotation.dart';

part 'example.g.dart';

@JsonSerializable()
class Post {
  int userId;
  int id;
  String title;
  String body;

  Post() {}
  factory Post.fromJson(Map<String, dynamic> json) => _$PostFromJson(json);
  Map<String, dynamic> toJson() => _$PostToJson(this);
  @override
  String toString() => 'Post {userId = $userId, id = $id, title = "$title", body = "${body?.replaceAll("\n", r"\n")}"}';
}

String baseUrl = 'http://jsonplaceholder.typicode.com/';

Future<String> getPostAsString() async {
  final response = await http.get("${baseUrl}posts/1");
  return response.body;
}

Future<Post> getPostAsJson() async {
  final response = await http.get("${baseUrl}posts/1");
  return Post.fromJson(json.decode(response.body));
}

Future<List<Post>> getPosts() async {
  final response = await http.get("${baseUrl}posts");
  final j = json.decode(response.body);
  return (j as List).map((e) => Post.fromJson(e)).take(2).toList();
}

Future<String> createPost() async {
  final o = Post()
    ..id = 0
    ..userId = 1
    ..title = 'test title'
    ..body = 'test body';
  final response = await http.post("${baseUrl}posts", body: json.encode(o));
  return response.body;
}

Future<String> updatePost() async {
  final o = Post()
    ..id = 1
    ..userId = 1
    ..title = 'test title'
    ..body = 'test body';
  final response = await http.put("${baseUrl}posts/1", body: json.encode(o));
  return response.body;
}

Future<String> deletePost() async {
  final response = await http.delete("${baseUrl}posts/1");
  return response.body;
}

Future httpTest() async {
  print(await getPostAsString());
  print(await getPostAsJson());
  print(await getPosts());
  print(await createPost());
  print(await updatePost());
  print(await deletePost());
}

void main() {
  httpTest();
}
  • getPostAsString 函数取出第1个Post,返回字符串
  • getPostAsJson 函数取出第1个Post,返回Post对象
  • getPosts 函数取出前2个Post,返回2个Post对象
  • createPost 函数创建1个Post,返回字符串
  • updatePost 函数更新第1个Post,返回字符串
  • deletePost 函数删除第1个Post,返回字符串

生成 json 转换的代码

在工程根目录下执行以下命令

pub run build_runner build

该命令会生成 example.g.dart 文件

// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'example.dart';

// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************

Post _$PostFromJson(Map<String, dynamic> json) {
  return Post()
    ..userId = json['userId'] as int
    ..id = json['id'] as int
    ..title = json['title'] as String
    ..body = json['body'] as String;
}

Map<String, dynamic> _$PostToJson(Post instance) => <String, dynamic>{
      'userId': instance.userId,
      'id': instance.id,
      'title': instance.title,
      'body': instance.body,
    };

输出

程序执行后的输出为

{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
Post {userId = 1, id = 1, title = "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", body = "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"}
[Post {userId = 1, id = 1, title = "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", body = "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"}, Post {userId = 1, id = 2, title = "qui est esse", body = "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"}]
{
  "id": 101
}
{
  "id": 1
}
{}

posted on 2020-09-17 16:47  zwvista  阅读(442)  评论(0编辑  收藏  举报