JSON handling in Flutter

Code Snippets 4 U

Needed packages:

  1. json_annotation: As regular dependency.
  2. build_runner: As dev dependency.
  3. json_serializable: As dev dependency.

E.g. class:

import 'package:json_annotation/json_annotation.dart'; // This packages needs to installed
part 'categories.g.dart';

@JsonSerializable(explicitToJson: true) // explicitToJson helps with nested objects
class Categories {
  int id;
  String name;
  String description;

  Categories({this.id, this.name, this.description, this.quizes});

  factory Categories.fromJson(Map<String, dynamic> json) => _$CategoriesFromJson(json);
  Map<String, dynamic> toJson() => _$CategoriesToJson(this);
}

After it run command:

flutter pub run build_runner build

Generated part file:

// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'categories.dart';

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

Categories _$CategoriesFromJson(Map<String, dynamic> json) {
  return Categories(
    id: json['id'] as int,
    name: json['name'] as String,
    description: json['description'] as String
  );
}

Map<String, dynamic> _$CategoriesToJson(Categories instance) =>
    <String, dynamic>{
      'id': instance.id,
      'name': instance.name,
      'description': instance.description
    };

Now whenever you want to convert to json or from json, use following syntax:

import 'dart:convert';

class example {
    var categoryObject = jsonDecode(categoryJsonString);
    var categoryJsonString = Category.toJson(categoryObject);
}

Leave a Reply

Your email address will not be published. Required fields are marked *

four + 2 =