A JSON serialize class to convert 'to' and 'from' JSON format Enums, DateTime and any of your own classes.

Related tags

Templates jsonize
Overview

A JSON serialize class to convert 'to' and 'from' JSON format Enums, DateTime and any of your own classes.

Introduction

Jsonize solves the problem of serializing and deserializing in JSON format objects into undefined structures.
This package does not implement the 'toJson' and 'fromJson' methods for you. For that you can use one of the many available packages like json_serializable.

Usage

By default Jsonize supports Enums and DateTime serialization in any place of your data structure.

  enum Color { red, blue, green, gray, yellow }
  Jsonize.registerEnum(Color.values);

  List<dynamic> myList = [1, "Hello!", Color.blue, DateTime.now()];

  var jsonRep = Jsonize.toJson(myList);
  var myDeserializedList = Jsonize.fromJson(jsonRep);
  print(myDeserializedList);

Jsonize also supports your own classes. You can register a type or let your class implement one of the Jsonizable or Clonable interfaces for classes and JsonizableEnum interface for keeping Enum serialization safe.

{ String? str; MyClass([this.str]); factory MyClass.empty() => MyClass(); // Jsonizable implementation @override String get jsonClassCode => "mc"; @override dynamic toJson() => str; @override MyClass? fromJson(value) => MyClass(value); } void main() { // Register enums and classes Jsonize.registerEnum(Color.values); Jsonize.registerClass(MyClass.empty()); Map myMap = { "my_num": 1, "my_str": "Hello!", "my_color": Color.green, "my_dt": DateTime.now(), "my_class": MyClass("here I am!") }; var jsonRep = Jsonize.toJson(myMap); var hereIsMyMap = Jsonize.fromJson(jsonRep); print(hereIsMyMap); }">
import 'package:jsonize/jsonize.dart';

enum Color with JsonizableEnum {
  /// The [jsonValue] must not change in time!
  red(10), // Can be numbers
  blue(20),
  green("myGreen"), // Can be strings as well
  gray(40),
  yellow(50);

  @override
  final dynamic jsonValue;
  const Color(this.jsonValue);
}

class MyClass implements Jsonizable<MyClass> {
  String? str;
  MyClass([this.str]);
  factory MyClass.empty() => MyClass();

  // Jsonizable implementation
  @override
  String get jsonClassCode => "mc";
  @override
  dynamic toJson() => str;
  @override
  MyClass? fromJson(value) => MyClass(value);
}

void main() {
  // Register enums and classes
  Jsonize.registerEnum(Color.values);
  Jsonize.registerClass(MyClass.empty());

  Map<String, dynamic> myMap = {
    "my_num": 1,
    "my_str": "Hello!",
    "my_color": Color.green,
    "my_dt": DateTime.now(),
    "my_class": MyClass("here I am!")
  };
  var jsonRep = Jsonize.toJson(myMap);
  var hereIsMyMap = Jsonize.fromJson(jsonRep);
  print(hereIsMyMap);
}

The Clonable interface is more compact, you only have to define fields of your object. An advantage of defining fields is that you can define optional default values which will not be set into the final JSON representation in order to save space.
Since it has to set object variables after creation you might not define them as 'final'. In case of 'final' members you can call the class constructor using the 'json' parameter within the 'create' method.
The Clonable interface has the 'before' and 'after' encoding and decoding events you can override to customize as you wish.

"$name - $r.$g.$b"; // Clonable implementation @override String get jsonClassCode => "colItem"; @override ColorItem create(json) => ColorItem(json["name"]); @override CloneFields get fields => CloneFields([ CloneField("name", getter: () => name, setter: (_) {}), CloneField("r", getter: () => r, setter: (v) => r = v, defaultValue: 0), CloneField("g", getter: () => g, setter: (v) => g = v, defaultValue: 0), CloneField("b", getter: () => b, setter: (v) => b = v, defaultValue: 0) ]); } void main() { // Register classes Jsonize.registerClass(ColorItem.empty()); List myList = [ ColorItem("Red", r: 255), ColorItem("Blue", b: 255), ColorItem("Gray", r: 128, g: 128, b: 128) ]; // Zeros will not be serialized since they are defined as default value. // This way you might save json data storage space. var jsonRep = Jsonize.toJson(myList); var backToLife = Jsonize.fromJson(jsonRep); print(backToLife); }">
import 'package:jsonize/jsonize.dart';

class ColorItem extends Clonable<ColorItem> {
  final String name;
  int r, g, b;
  ColorItem(this.name, {this.r = 0, this.g = 0, this.b = 0});
  factory ColorItem.empty() => ColorItem("");

  @override
  String toString() => "$name - $r.$g.$b";

  // Clonable implementation
  @override
  String get jsonClassCode => "colItem";

  @override
  ColorItem create(json) => ColorItem(json["name"]);

  @override
  CloneFields get fields => CloneFields([
        CloneField("name", getter: () => name, setter: (_) {}),
        CloneField("r", getter: () => r, setter: (v) => r = v, defaultValue: 0),
        CloneField("g", getter: () => g, setter: (v) => g = v, defaultValue: 0),
        CloneField("b", getter: () => b, setter: (v) => b = v, defaultValue: 0)
      ]);
}

void main() {
  // Register classes
  Jsonize.registerClass(ColorItem.empty());

  List myList = [
    ColorItem("Red", r: 255),
    ColorItem("Blue", b: 255),
    ColorItem("Gray", r: 128, g: 128, b: 128)
  ];

  // Zeros will not be serialized since they are defined as default value.
  // This way you might save json data storage space.
  var jsonRep = Jsonize.toJson(myList);
  var backToLife = Jsonize.fromJson(jsonRep);
  print(backToLife);
}

For more complex cases like subclasses, please refer to the examples section.

Jsonize methods

toJson

static String toJson(dynamic value,
      {String? indent,
       String? jsonClassToken,
       String? dtClassCode,
       DateTimeFormat dateTimeFormat = DateTimeFormat.string,
       CallbackFunction? convertCallback})

Transforms an object/structure of objects into a JSON string applying the class tokens in order to revert back your original objects.

Parameters:

  • value: the value you want to transform to JSON string.
  • indent: The indentation token. If omitted no indentation is used (space saving!).
  • jsonClassToken: The token used by Jsonize to identify a serialized object.
  • dtClassCode: The code used to serialize DateTime objects.
  • dateTimeFormat: The DateTime serialization format (see DateTimeFormat enum).
  • convertCallback: An optional function called before returning the object's encoded JSON representation.

fromJson

  static dynamic fromJson(dynamic value,
      {String? jsonClassToken,
       String? dtClassCode,
       DateTimeFormat dateTimeFormat = DateTimeFormat.string,
       CallbackFunction? convertCallback})

Transforms a JSON string back to an object/structure of objects.

Parameters:

  • value: the value you want to transform to JSON string.
  • jsonClassToken: The token used by Jsonize to identify a serialized object.
  • dtClassCode: The code used to serialize DateTime objects.
  • dateTimeFormat: The DateTime serialization format (see DateTimeFormat enum).
  • convertCallback: An optional function called before decoding the JSON representation into the object.

registerEnum

  static void registerEnum<T>(List<T> values,
      {String? jsonEnumCode, 
      EnumFormat enumFormat = EnumFormat.string,
      Enum? unknownEnumValue}) {

Registers a new Enum type.

Parameters:

  • values: The values of the enumeration type (i.e. myEnum.values).
  • jsonEnumCode: An optional code used to serialize these Enum items. If not provided the Enum name will be taken.
  • enumFormat: The serialization format (see EnumFormat).
  • unknownEnumValue: This optional parameter is used during decoding in case of an unrecognized value. This can happen if an old json holds a removed enum. Note: 'unknownEnumValue' is not applicable to 'EnumFormat.indexOf'

registerClass

static void registerClass(Jsonizable object)

Registers a new Jsonizable class by it instance.

Parameters:

  • object: the class instance jsonize will be able to serialize.

registerClasses

static void registerClasses(Iterable<Jsonizable> objects)

Registers new Jsonizable classes by it instances.

Parameters:

  • objects: the class instances jsonize will be able to serialize.

registerType

static void registerType(Type classType,
      String classTypeCode,
      ConvertFunction? toJsonFunc,
      ConvertFunction? fromJsonFunc)

Registers a new type to the Jsonize conversion handling (i.e. used for classes that does not implement Jsonizable interface)

Parameters:

  • type: the type jsonize will be able to serialize.
  • classTypeCode: the class type token jsonize will use to identify this object type/class.
  • toJsonFunc: the JSON encoder function.
  • fromJsonFunc: the JSON decoder function.

Jsonize enums

DateTimeFormat

  • string: a human readable date time string representation.
  • stringWithMillis: a human readable date time string representation with milliseconds.
  • stringWithMicros: a human readable date time string representation with microseconds.
  • epoch: a number representing the seconds since the "Unix epoch" 1970-01-01T00:00:00 (JSON space saver!).
  • epochWithMillis: a number representing the milliseconds since the "Unix epoch" 1970-01-01T00:00:00.
  • epochWithMicros: a number representing the microseconds since the "Unix epoch" 1970-01-01T00:00:00.

EnumFormat

  • string: the text of the enum item.
  • indexOf: the index of the enum item.

Both formats have pro & cons.

string

  • it is space consuming since it's the text of the item
  • you can not change the item text
  • you can add new items without warring about its position

indexOf

  • it saves space since it is only a number
  • you can change the item text
  • you can not add new items without warring about its position

Additional information

Since current Dart implementation does not really support reflection, Jsonize requires what I would define as two extra steps:

  1. register all your types/classes you want to serialize
  2. In case of implementing the Jsonizable interface, you will need to register a class instance (e.g. factory MyClass.empty() => ...)

I hope future Dart releases will support better reflection and type handling.

You might also like...

Extensões para DateTime em pt_BR

brasil_datetime Extensões para a classe DateTime para facilitar a formatação em pt_BR. Apresentação Este package facilita a manipulação de objetos Dat

Dec 29, 2022

An application used to manage all your tabs in a clean, scrollable, categorized format.

An application used to manage all your tabs in a clean, scrollable, categorized format.

Tabmanager Created by Sami-ul You can contact me here: [email protected] Recent updates Made the app run faster by using the backend to serve t

Nov 2, 2022

A cross-platform flutter package to convert your links into rich beautiful previews.

A cross-platform flutter package to convert your links into rich beautiful previews.

Link Preview Generator A cross-platform flutter package to convert your links into rich beautiful previews. This package is inspired from Any Link Pre

Oct 21, 2022

This is a Flutter app which shows how to use the PageView Class in your Flutter App

page_view_class A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started

Oct 25, 2021

Flashcard App where you can learn different topics and create your own flashcards in Google Drive.

flashcard_project Flashcard app connected with Google Spreadsheet Getting Started This is a Flutter Project that works on iOS, Android, Web and MacOS.

Oct 24, 2022

An extended version of Flutter Colors with more swatches and more flexibility to generate your own custom swatch.

An extended version of Flutter Colors with more swatches and more flexibility to generate your own custom swatch.

Colours An extended version of Flutter Colors with more swatches and more flexibility to generate your own custom swatch. Getting Started In your flut

Nov 23, 2021

Stream Chat official Flutter SDK. Build your own chat experience using Dart and Flutter.

Stream Chat official Flutter SDK. Build your own chat experience using Dart and Flutter.

Official Flutter packages for Stream Chat Quick Links Register to get an API key for Stream Chat Flutter Chat SDK Tutorial Chat UI Kit Sample apps Thi

Dec 25, 2022

Use the template to create your own repository, complete the project and verify

Use the template to create your own repository, complete the project and verify

Proyecto Nivelación MisionTic Usar el template para crear un repositorio propio,

Dec 20, 2021

A library that makes it easy for you to create your own custom wizard.

A library that makes it easy for you to create your own custom wizard.

Flutter Wizard Author: Jop Middelkamp A library that makes it easy for you to create your custom wizard. You'll have 100% control over the appearance

Dec 2, 2022
Owner
null
A simple dart package to convert large numbers to a human readable format. 1278 to 1.2K instead, for example.

A simple dart package to convert large numbers to a human readable format. 1278 to 1.2K instead, for example. Features Represents large numbers in ter

Rohit V 1 Oct 8, 2022
Given a JSON string, this library will generate all the necessary Dart classes to parse and generate JSON.

JSON to Dart Given a JSON string, this library will generate all the necessary Dart classes to parse and generate JSON. This library is designed to ge

Javier Lecuona 1.2k Dec 25, 2022
A new Flutter project. Use of Padding Class(Widget) and Card Class (Widget)

Use_Of_Card_And_Padding_Class A new Flutter project. Use of Padding Class(Widget) and Card Class (Widget) Getting Started This project is a starting p

Avinandan Bose 1 Mar 18, 2022
A free tool to convert any website into a cross platform native application.

SWAB (Spyxpo Web to App Builder) Convert any website into an iOS/Android/Windows/macOS/Linux app. This is a preview build for testing purposes major u

Spyxpo 7 Jan 1, 2023
Find underused colors, overused magical numbers and the largest classes in any Flutter project.

Flutter Resource Ranker It is easy to overuse colors, write magical numbers or long classes. This project has a script to help you detect these. This

Bernardo Ferrari 24 Jul 12, 2021
validate JSON against your own Blueprint 👑🧬

PART OF QUEEN ?? Validate JSON Against Your Own Blueprint ?? ?? Content Validate JSON Against Your Own Blueprint ?? ?? Content Motivation NOTE Feature

FlutterQueen 12 Oct 29, 2022
Convert Json to Form for Flutter apps

Convert Json to Form for Flutter apps. ?? Star and Share ?? the repo to support the project. Thanks! A flutter plugin to use convert Json to Form Exam

Victor Alfonso Rodas Oña 95 Dec 19, 2022
Flutter shareable package of object-oriented classes for local caching of user data in json

json_cache Json Cache is an object-oriented package to serve as a layer on top of local storage packages - packages that persist data locally on the u

Dartoos 10 Dec 19, 2022
A generator for fhir dart classes with json artifacts.

A generator for fhir dart classes with json artifacts. Thie generator uses the freezed package to generate the data classes. It also uses all the primitive_types from the fhir package.

Joel Staubach 2 Jun 14, 2022
🎯 This library automatically generates object classes from JSON files that can be parsed by the freezed library.

The Most Powerful Way to Automatically Generate Model Objects from JSON Files ⚡ 1. Guide ?? 1.1. Features ?? 1.1.1. From 1.1.2. To 1.2. Getting Starte

KATO, Shinya / 加藤 真也 14 Nov 9, 2022