json_serializable 0.5.0
json_serializable: ^0.5.0 copied to clipboard

outdated Dart 2 incompatible

Generates utilities to aid in serializing to/from JSON.

Build Status

Provides source_gen Generators to create code for JSON serialization and deserialization.

See the example package to understand how to configure your project.

User defined and generated code #

Given a library example.dart with an Person class annotated with @JsonSerializable():

import 'package:json_annotation/json_annotation.dart';

part 'example.g.dart';

class Person extends Object with _$PersonSerializerMixin {
  final String firstName;
  final String lastName;

  final DateTime dateOfBirth;

  Person({this.firstName, this.lastName, this.dateOfBirth});

  factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);

Building creates the corresponding part example.g.dart:

part of 'example.dart';

Person _$PersonFromJson(Map<String, dynamic> json) => new Person(
    firstName: json['firstName'] as String,
    lastName: json['lastName'] as String,
    dateOfBirth: json['dateOfBirth'] == null
        ? null
        : DateTime.parse(json['dateOfBirth'] as String));

abstract class _$PersonSerializerMixin {
  String get firstName;
  String get lastName;
  DateTime get dateOfBirth;
  Map<String, dynamic> toJson() => <String, dynamic>{
        'firstName': firstName,
        'lastName': lastName,
        'dateOfBirth': dateOfBirth?.toIso8601String()