Dart 處理json,built_value庫

原文連接
文檔html

import 'dart:convert';

main() async {
  // json 轉化爲 map
  String jsonStr = '''
    [
      {"name": "ajanuw"},
      {"name": "suou"}
    ]
  ''';

  var jsonObj = jsonDecode(jsonStr);
  print(jsonObj[0]['name'] == 'ajanuw'); // true

  // list<Map> 轉化爲 json字符串
  var scores = [
    {'score': 40},
    {'score': 80},
    {'score': 100, 'overtime': true, 'special_guest': null}
  ];
  var jsonText = jsonEncode(scores);
  print(jsonText);
}

使用對象添加模板 JSON to Dart

import 'dart:convert';

class MyInfo {
  MyInfo({this.age, this.name});

  String name;
  int age;

  factory MyInfo.fromJson(Map<String, dynamic> jsonMap) {
    return MyInfo(
      name: jsonMap['name'],
      age: jsonMap['age'],
    );
  }
}

main(List<String> args) {
  String jsonStr = '''
    {
      "name": "ajanuw",
      "age": 12
    }
  ''';
  var parsed = jsonDecode(jsonStr);
  MyInfo data = MyInfo.fromJson(parsed);
  print(data.age);
}

使用「built_value」庫來處理json

我在這裏使用"stagehand console-full"建立的項目示例,項目名叫"dart_test"git

1) 安裝依賴github

dependencies:
  ...
  built_value:
  built_collection:

dev_dependencies:
  ...
  build_runner:
  built_value_generator:

2) 準備json數據json

{
      "id": 157538,
      "date": "2017-07-21T10:30:34",
      "date_gmt": "2017-07-21T17:30:34",
      "type": "post",
      "link": "https://example.com",
      "title": {
          "rendered": "Json 2 dart built_value converter"
      },
      "tags": [
          1798,
          6298
      ]
}

3) 建立文件"lib/models/hello.dart",文件名很重要必需要要和你的class名同樣async

import 'dart:convert';

import 'package:built_collection/built_collection.dart';
import 'package:built_value/built_value.dart';
import 'package:built_value/serializer.dart';

part 'hello.g.dart';

abstract class Hello implements Built<Hello, HelloBuilder> {
  Hello._();

  factory Hello([updates(HelloBuilder b)]) = _$Hello;

  @BuiltValueField(wireName: 'id')
  int get id;
  @BuiltValueField(wireName: 'date')
  String get date;
  @BuiltValueField(wireName: 'date_gmt')
  String get dateGmt;
  @BuiltValueField(wireName: 'type')
  String get type;
  @BuiltValueField(wireName: 'link')
  String get link;
  @BuiltValueField(wireName: 'title')
  Title get title;

  @nullable // 可爲空,返回null
  @BuiltValueField(wireName: 'tags')
  BuiltList<int> get tags;

  String toJson() {
    return jsonEncode(serializers.serializeWith(Hello.serializer, this));
  }

  static Hello fromJson(String jsonString) {
    return serializers.deserializeWith(
        Hello.serializer, jsonDecode(jsonString));
  }

  static Serializer<Hello> get serializer => _$helloSerializer;
}

abstract class Title implements Built<Title, TitleBuilder> {
  Title._();

  factory Title([updates(TitleBuilder b)]) = _$Title;

  @BuiltValueField(wireName: 'rendered')
  String get rendered;

  String toJson() {
    return jsonEncode(serializers.serializeWith(Title.serializer, this));
  }

  static Title fromJson(String jsonString) {
    return serializers.deserializeWith(
        Title.serializer, jsonDecode(jsonString));
  }

  static Serializer<Title> get serializer => _$titleSerializer;
}

4) 保存文件後,在項目根目錄下運行命令, 生成"lib/models/hello.g.dart"文件ide

flutter packages pub run build_runner build   // 執行一次build命令
flutter packages pub run build_runner watch  // 文件更改自動build
flutter packages pub run build_runner watch --delete-conflicting-outputs  // 刪除舊文件在build

5) 建立"lib/models/serializers.dart"文件,編寫下面的代碼後,保存會生成"lib/models/serializers.g.dart"文件post

import 'package:built_collection/built_collection.dart';
import 'package:built_value/serializer.dart';
import 'package:built_value/standard_json_plugin.dart';
import 'package:dart_test/models/hello.dart';

part 'serializers.g.dart';

@SerializersFor(const [
  Hello
])
final Serializers serializers = (_$serializers.toBuilder()..addPlugin(StandardJsonPlugin())).build();

6) 編寫「bin/main.dart"ui

import 'package:dart_test/models/hello.dart';

String jsonStr = '''
 {
      "id": 157538,
      "date": "2017-07-21T10:30:34",
      "date_gmt": "2017-07-21T17:30:34",
      "type": "post",
      "link": "https://example.com",
      "title": {
          "rendered": "Json 2 dart built_value converter"
      },
      "tags": [
          1798,
          6298
      ]
    }
''';

main(List<String> args) {
  Hello hello = Hello.fromJson(jsonStr);
  print(hello.title.rendered);
  print(hello.tags.length);
}

7) 保存文件後執行this

> dart bin/main.dart
Json 2 dart built_value converter
2

在vscode中隱藏 「*.g.dart」生成的文件

"files.exclude": {
    "**/*.g.dart": true
  }

built_value處理json不要有這樣的數據 { key: [[{}], [{}],...] } 轉換爲這樣: { key: [{key: []}, {key: []},...] }code

建立枚舉

int get age;
  TypeStatus get type => age < 10 ? TypeStatus.a : TypeStatus.b;

enum TypeStatus {
  a,
  b,
}
 // or
class TypeStatus extends EnumClass {
  static const TypeStatus a = _$a;
  static const TypeStatus b = _$b;
  const TypeStatus._(String name) : super(name);
  static BuiltSet<TypeStatus> get values => _$values;
  static TypeStatus valueOf(String name) => _$valueOf(name);
}
相關文章
相關標籤/搜索