0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

FlutterのjsonEncode / toJson

Posted at

1. jsonEncode

Dart標準ライブラリ dart:convert の関数。
MapやListをJSON文字列に変換する

import 'dart:convert';

final map = {"id": "1", "text": "買い物"};
final jsonStr = jsonEncode(map);
print(jsonStr); 
// => '{"id":"1","text":"買い物"}'  ← Stringになった

2. toJson

Freezedやjson_serializableが自動生成してくれる関数
クラスのインスタンスを Map<String, dynamic> に変換する。

final post = PostLocal(
  id: "1",
  text: "買い物",
  status: ReminderStatus.pending,
  timezone: "Asia/Tokyo",
);

final map = post.toJson();
print(map);
// => {"id":"1","text":"買い物","status":"pending","timezone":"Asia/Tokyo"}

toJson() の出力は Map
それを jsonEncode に渡すと 文字列 になる。
toJsonStr() => jsonEncode(toJson()); でMap→文字列

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?