Git Product home page Git Product logo

json_fields's Introduction

Pub Package

Hi! ๐Ÿ‘‹ , This is JSON Fields, a package that helps you to work with JSON data.

package:json_fields is a library that generates a class to access the serialized names of the fields in your Dart Object.

Motivation ๐Ÿ’ช

I have frequently come across situations where I want to store a JSON object in a database, but I don't want to update the entire object every time I make a change.

The only way to get around this was to type out the key/field name in the request or create a static variable within the class. All of this is tedious, prone to typos/incorrect formatting/errors, its not DRY, and can require all developers working on the project to know the DB structure. ๐Ÿ˜ฃ ๐Ÿ˜ฌ

package:json_fields leverages package:json_annotation to create the fields class, making a fast addition to your already serialized classes.

Setup ๐Ÿ–ฅ

To configure your project for the latest released version of json_fields see the example.

Example ๐Ÿง

Also see the example

In example.dart we have a Person class annotated with @JsonSerializable:

import 'package:json_annotation/json_annotation.dart';

part 'example.g.dart';

@JsonSerializable()
class Person {
  /// The generated code assumes these values exist in JSON.
  final String firstName, lastName;

  /// The generated code below handles if the corresponding JSON value doesn't
  /// exist or is empty.
  final DateTime? dateOfBirth;

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

  /// Connect the generated [_$PersonFields] class to the fields getter.
  static _$PersonFields get fields => _$PersonFields();


  // --- json_serializable ---
  //! fromJson & toJson are not required to use `json_fields`
  //! but they are included here for completeness.

  /// Connect the generated [_$PersonFromJson] function to the `fromJson`
  /// factory.
  factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);

  /// Connect the generated [_$PersonToJson] function to the `toJson` method.
  Map<String, dynamic> toJson() => _$PersonToJson(this);

}

Building creates the corresponding part example.g.dart:

// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'example.dart';

// **************************************************************************
// JsonFieldsGenerator
// **************************************************************************

class _$PersonFields {
  const _$PersonFields();
  final String firstName = 'firstName';
  final String lastName = 'lastName';
  final String dateOfBirth = 'dateOfBirth';
}

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

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

Map<String, dynamic> _$PersonToJson(Person instance) => <String, dynamic>{
      'firstName': instance.firstName,
      'lastName': instance.lastName,
      'dateOfBirth': instance.dateOfBirth?.toIso8601String(),
    };

Accessing the JSON key fields:

{
  // 'firstName': 'John'
  Person.fields.firstName: 'John',
}

Running the code generator ๐Ÿƒโ€โ™‚๏ธ

Once you have added the annotations to your code you then need to run the code generator to generate the missing .g.dart generated dart files.

If this file already exists, the json_fields tool will prepend the generated code

In your package directory you can run the following command:

  • For Dart: dart run build_runner build

  • For Flutter: flutter pub run build_runner build

Annotation values ๐Ÿ˜Ž

The only annotation required to use this package is JsonSerializable. When applied to a class (in a correctly configured package), the fields class will be generated when you build. There are three ways to control how code is generated:

  1. Setting properties on JsonKey annotating the target field.
  2. Set properties on JsonSerializable annotating the target type.
  3. Add configuration to build.yaml โ€“ more here.

for more information: package:json_serializable

json_fields's People

Contributors

mrgnhnt96 avatar

Watchers

 avatar

json_fields's Issues

Options for multiple formats?

Would it be helpful to specify formats that fields should be generated in?

for example

// Class is/is not annotated with `additionalFormats: []` (default)
Example.fields.firstName // returns 'firstName'

// Class is annotated with `additionalFormats: [FieldRename.snake, FieldRename.kebab]`
Example.fields.defaults.firstName // returns 'firstName'
Example.fields.snake.firstName // returns 'first_name'
Example.fields.kebab.firstName // returns 'first-name'

Access sub fields

Think of a way to access this

class Person {
   final Purchase purchase;
...
}

class Purchase {
   final Sting product;
...
}

How could we access Person.purchase.product?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.