Dart Json サンプル
自分用のDartのJsonのサンプルです。
このような簡単なDartのプログラムを確認のために実行するときはこのサイトを利用します。
import 'dart:convert';
void main() {
String jsonString = '''
{
"name": "徳川家康",
"email": "tokugawa@example.com"
}''';
Map<String, String> json_ = {
"name": "織田信長",
"email": "oda@example.com"
};
//Map<String, dynamic> aaa =
List<Map<String, dynamic>> jsonList = [
{ "name": "織田信長", "email": "oda@example.com" },
{ "name": "織田信長", "email": "oda@example.com" },
];
print(jsonString);
var jsonMap = jsonDecode(jsonString);
//assert(jsonMap is Map);
print(jsonMap);
Map<String, dynamic> map = jsonDecode(jsonString);
print(map['name']);
print(json_);
print(jsonList);
}
結果
{
"name": "徳川家康",
"email": "tokugawa@example.com"
}
{name: 徳川家康, email: tokugawa@example.com}
徳川家康
{name: 織田信長, email: oda@example.com}
[{name: 織田信長, email: oda@example.com}, {name: 織田信長, email: oda@example.com}]
Contents
その2
jsonListString は、jsonのリスト(配列)の文字列です。
これをjsonDecodeして利用します。
import 'dart:convert';
void main() {
String jsonListString = '''[
{
"name": "豊臣秀吉",
"email": "toyotomi@example.com"
},
{
"name": "徳川家康",
"email": "tokugawa@example.com"
}
]''';
var jsonMap2 = jsonDecode(jsonListString);
print(jsonMap2);
print(jsonMap2.length);
print(jsonMap2[0]);
print(jsonMap2[0]['name']);
}