A Generator to Create Config Class From json Files

A generator to create config class from json files that support many environments.

Motivation

If you use a json file to config your applications, perphaps you need to write a dart class that contain all variables you define with their data types. When you need to manage nested objects is more complicated. Even if you want to add or delete a value in your json, you need to modify your dart class.

If you want to manage environments you need to writte manually the file path for every enviroment you need.

json_config_generator wants to help you to have an easy process with the manage of config files and environments.

Install

To use json_config_generator, you will need build_runner/code-generator setup.
First, install build_runner and json_config_generator by adding them to your pubspec.yaml file:

pubspec.yaml

dependencies:
  json_config_annotation: ^0.1.0

dev_dependencies:
  build_runner:
  json_config_generator: ^0.1.0

How to use

To use this generator need to create an empty config dart class that begins with $ using the annotation Configuration defining the environments that you want to have. Each environment has name and path, if have more that one, the generator create an Enum to environments. Also you can specify the name of that Enum. By default it's name is Environment. Also, you need to add some imports.

config.dart

import 'package:json_config_annotation/json_config_annotation.dart';
import 'dart:convert';
import 'package:flutter/services.dart';

part 'config.g.dart'; //{dart file name}.g.dart

@Configuration(
  environmentEnumName: 'Env',
  environments:[
    Environment(name:'dev', path:'assets/config/dev.json'),
    Environment(name:'prd', path:'assets/config/prd.json'),
  ],
)
class $Config{}

suposing that have the next json file

dev.json

{
  "base_url": "https://example.com",
  "custom_class": {
    "value_1": "dfgdfgdfgwqrrqwrqwrqweqwe324523b252dghfdhd",
    "value_2": "6Lez7aIaAAAAAN6qZG2343c252bv66b7yn5m8m6"
  },
  "int_value": 3,
  "double_value": 3.5,
  "boolean_value": true,
  "string_list": ["hello", "world"],
  "int_list": [1, 23, 5],
  "bool_list": [false, true, true],
  "custom_list": [
    {
      "value_1": "hello"
    },
    {
      "value_1": "world"
    }
  ]
}

the generator creates

config.g.dart

enum Env { dev, prd }

class Config {
  Config._();

  static final instance = Config._();

  late String baseUrl;

  late _CustomClass customClass;

  late int intValue;

  late double doubleValue;

  late bool booleanValue;

  late List<String> stringList;

  late List<int> intList;

  late List<bool> boolList;

  late List<_CustomList> customList;

  Future<void> init(Env env) async {
    String path = '';
    switch (env) {
      case Env.dev:
        path = 'assets/config/dev.json';
        break;
      case Env.prd:
        path = 'assets/config/prd.json';
        break;
    }
    final jsonString = await rootBundle.loadString(path);
    final config = json.decode(jsonString) as Map<String, dynamic>;
    baseUrl = config['base_url'] as String;
    customClass =
        _CustomClass.fromJson(config['custom_class'] as Map<String, dynamic>);
    intValue = config['int_value'] as int;
    doubleValue = config['double_value'] as double;
    booleanValue = config['boolean_value'] as bool;
    stringList = (config['string_list'] as List).cast<String>();
    intList = (config['int_list'] as List).cast<int>();
    boolList = (config['bool_list'] as List).cast<bool>();
    customList = _CustomList.listFromJson(config['custom_list'] as List);
  }
}

class _CustomClass {
  const _CustomClass({required this.value1, required this.value2});

  factory _CustomClass.fromJson(Map<String, dynamic> customClass) =>
      _CustomClass(
        value1: customClass['value_1'] as String,
        value2: customClass['value_2'] as String,
      );

  final String value1;

  final String value2;
}

class _CustomList {
  const _CustomList({required this.value1});

  factory _CustomList.fromJson(Map<String, dynamic> customList) => _CustomList(
        value1: customList['value_1'] as String,
      );

  final String value1;

  static List<_CustomList> listFromJson(List data) =>
      data.map((e) => _CustomList.fromJson(e as Map<String, dynamic>)).toList();
}

To use the generated configuration you need to call init method to initialize all values. Could be called in main defining the Environment that you want to use.

main.dart

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Config.instance.init(Env.dev);
  runApp(const MyApp());
}

Now can access to fields easy using the instance

Config.instance.baseUrl;
Config.instance.customClass.value1;

Supported data types

- String
- int
- double
- bool
- CustomClass
- List<String>
- List<int>
- List<double>
- List<bool>
- List<CustomClass>

Also can create nested classes!

Important

  • Do not support nullable values
  • Do not support dynamic values

Run the generator

To run the generator use one of the next commands:

  • flutter pub run build_runner build
  • dart pub run build_runner build

Considerations

Can also create a config with only one Environment. If that so, the Enum do not be created and when call init method, do not need to pass any argument.

It is important to known that the generator takes the first value in lists to known the type of the list, so be caferull

Use this package as a library

Depend on it

Run this command:

With Dart:

 $ dart pub add json_config_generator

This will add a line like this to your package's pubspec.yaml (and run an implicit dart pub get):

dependencies:
  json_config_generator: ^0.1.2

Alternatively, your editor might support dart pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:json_config_generator/builder.dart'; 

example/README.md

import 'package:json_config_annotation/json_config_annotation.dart';
import 'dart:convert';
import 'package:flutter/services.dart';

part 'config.g.dart'; //{dart file name}.g.dart

@Configuration(
  environmentEnumName: 'Env',
  environments:[
    Environment(name:'dev', path:'assets/config/dev.json'),
    Environment(name:'prd', path:'assets/config/prd.json'),
  ],
)
class $Config{} 

Download Details:

Author: deCardenas

Source Code: https://github.com/deCardenas/json_config_generator

#json  #flutter 

What is GEEK

Buddha Community

A Generator to Create Config Class From json Files
Brandon  Adams

Brandon Adams

1625637060

What is JSON? | JSON Objects and JSON Arrays | Working with JSONs Tutorial

In this video, we work with JSONs, which are a common data format for most web services (i.e. APIs). Thank you for watching and happy coding!

Need some new tech gadgets or a new charger? Buy from my Amazon Storefront https://www.amazon.com/shop/blondiebytes

What is an API?
https://youtu.be/T74OdSCBJfw

JSON Google Extension
https://chrome.google.com/webstore/detail/json-formatter/bcjindcccaagfpapjjmafapmmgkkhgoa?hl=en

Endpoint Example
http://maps.googleapis.com/maps/api/geocode/json?address=13+East+60th+Street+New+York,+NY

Check out my courses on LinkedIn Learning!
REFERRAL CODE: https://linkedin-learning.pxf.io/blondiebytes
https://www.linkedin.com/learning/instructors/kathryn-hodge

Support me on Patreon!
https://www.patreon.com/blondiebytes

Check out my Python Basics course on Highbrow!
https://gohighbrow.com/portfolio/python-basics/

Check out behind-the-scenes and more tech tips on my Instagram!
https://instagram.com/blondiebytes/

Free HACKATHON MODE playlist:
https://open.spotify.com/user/12124758083/playlist/6cuse5033woPHT2wf9NdDa?si=VFe9mYuGSP6SUoj8JBYuwg

MY FAVORITE THINGS:
Stitch Fix Invite Code: https://www.stitchfix.com/referral/10013108?sod=w&som=c
FabFitFun Invite Code: http://xo.fff.me/h9-GH
Uber Invite Code: kathrynh1277ue
Postmates Invite Code: 7373F
SoulCycle Invite Code: https://www.soul-cycle.com/r/WY3DlxF0/
Rent The Runway: https://rtr.app.link/e/rfHlXRUZuO

Want to BINGE?? Check out these playlists…

Quick Code Tutorials: https://www.youtube.com/watch?v=4K4QhIAfGKY&index=1&list=PLcLMSci1ZoPu9ryGJvDDuunVMjwKhDpkB

Command Line: https://www.youtube.com/watch?v=Jm8-UFf8IMg&index=1&list=PLcLMSci1ZoPvbvAIn_tuSzMgF1c7VVJ6e

30 Days of Code: https://www.youtube.com/watch?v=K5WxmFfIWbo&index=2&list=PLcLMSci1ZoPs6jV0O3LBJwChjRon3lE1F

Intermediate Web Dev Tutorials: https://www.youtube.com/watch?v=LFa9fnQGb3g&index=1&list=PLcLMSci1ZoPubx8doMzttR2ROIl4uzQbK

GitHub | https://github.com/blondiebytes

Twitter | https://twitter.com/blondiebytes

LinkedIn | https://www.linkedin.com/in/blondiebytes

#jsons #json arrays #json objects #what is json #jsons tutorial #blondiebytes

Marisol  Kuhic

Marisol Kuhic

1626642000

How to Create an Online Json File and a Pojo File for It

This tutorial will clearly explain you how to generate a static json file online for your app testing.Also not only generating json file you can create an online Pojo file for it and integrate the api easily into your project.

Subscribe this channel

http://www.youtube.com/channel/UCWCLzrDi9TVkAsE-l4ZAHVQ?sub_confirmation=1

For more tutorials visit : http://androidcoding.in/

Follow us

facebook : https://www.facebook.com/androidcoding.in

google : https://plus.google.com/u/0/105124287022524668610

#programming with vishal #json file #pojo file #generate

Hollie  Ratke

Hollie Ratke

1596823200

# Google's Flutter Tutorial- Easily Parse Complex JSON, Create JSON Model Classes.

Welcome to Flutter tutorial

This demo helps you to easily parse any complex JSON data in to Dart Model classe easily.
Proper Error Handling in Flutter
https://www.youtube.com/watch?v=yA_BI

Visit http://coderzheaven.com for more tutorials.

Please don’t forget to LIKE, SUBSCRIBE & SHARE.
Please leave your valuable comments in the comment section below.
Thanks for watching.

#json #create-json #json-data #flutter

Yashi Tyagi

1617449307

CA Classes - Best CA Classes Online

Chartered Accountancy course requires mental focus & discipline, coaching for CA Foundation, CA Inter and CA Finals are omnipresent, and some of the best faculty’s classes have moved online, in this blog, we are going to give the best way to find online videos lectures, various online websites provide the CA lectures, Smartnstudy one of the best site to CA preparation, here all faculty’s video lecture available.

check here : ca classes

#ca classes online #ca classes in delhi #ca classes app #ca pendrive classes #ca google drive classes #best ca classes online

How To Create User-Generated Content? [A Simple Guide To Grow Your Brand]

This is image title

In this digital world, online businesses aspire to catch the attention of users in a modern and smarter way. To achieve it, they need to traverse through new approaches. Here comes to spotlight is the user-generated content or UGC.

What is user-generated content?
“ It is the content by users for users.”

Generally, the UGC is the unbiased content created and published by the brand users, social media followers, fans, and influencers that highlight their experiences with the products or services. User-generated content has superseded other marketing trends and fallen into the advertising feeds of brands. Today, more than 86 percent of companies use user-generated content as part of their marketing strategy.

In this article, we have explained the ten best ideas to create wonderful user-generated content for your brand. Let’s start without any further ado.

  1. Content From Social Media Platforms
    In the year 2020, there are 3.81 million people actively using social media around the globe. That is the reason social media content matters. Whenever users look at the content on social media that is posted by an individual, then they may be influenced by their content. Perhaps, it can be used to gain more customers or followers on your social media platforms.

This is image title

Generally, social media platforms help the brand to generate content for your users. Any user content that promotes your brand on the social media platform is the user-generated content for your business. When users create and share content on social media, they get 28% higher engagement than a standard company post.

Furthermore, you can embed your social media feed on your website also. you can use the Social Stream Designer WordPress plugin that will integrate various social media feeds from different social media platforms like Facebook, Twitter, Instagram, and many more. With this plugin, you can create a responsive wall on your WordPress website or blog in a few minutes. In addition to this, the plugin also provides more than 40 customization options to make your social stream feeds more attractive.

  1. Consumer Survey
    The customer survey provides powerful insights you need to make a better decision for your business. Moreover, it is great user-generated content that is useful for identifying unhappy consumers and those who like your product or service.

In general, surveys can be used to figure out attitudes, reactions, to evaluate customer satisfaction, estimate their opinions about different problems. Another benefit of customer surveys is that collecting outcomes can be quick. Within a few minutes, you can design and load a customer feedback survey and send it to your customers for their response. From the customer survey data, you can find your strengths, weaknesses, and get the right way to improve them to gain more customers.

  1. Run Contests
    A contest is a wonderful way to increase awareness about a product or service. Contest not just helps you to enhance the volume of user-generated content submissions, but they also help increase their quality. However, when you create a contest, it is important to keep things as simple as possible.

Additionally, it is the best way to convert your brand leads to valuable customers. The key to running a successful contest is to make sure that the reward is fair enough to motivate your participation. If the product is relevant to your participant, then chances are they were looking for it in the first place, and giving it to them for free just made you move forward ahead of your competitors. They will most likely purchase more if your product or service satisfies them.

Furthermore, running contests also improve the customer-brand relationship and allows more people to participate in it. It will drive a real result for your online business. If your WordPress website has Google Analytics, then track contest page visits, referral traffic, other website traffic, and many more.

  1. Review And Testimonials
    Customer reviews are a popular user-generated content strategy. One research found that around 68% of customers must see at least four reviews before trusting a brand. And, approximately 40 percent of consumers will stop using a business after they read negative reviews.

The business reviews help your consumers to make a buying decision without any hurdle. While you may decide to remove all the negative reviews about your business, those are still valuable user-generated content that provides honest opinions from real users. Customer feedback can help you with what needs to be improved with your products or services. This thing is not only beneficial to the next customer but your business as a whole.

This is image title

Reviews are powerful as the platform they are built upon. That is the reason it is important to gather reviews from third-party review websites like Google review, Facebook review, and many more, or direct reviews on a website. It is the most vital form of feedback that can help brands grow globally and motivate audience interactions.

However, you can also invite your customers to share their unique or successful testimonials. It is a great way to display your products while inspiring others to purchase from your website.

  1. Video Content
    A great video is a video that is enjoyed by visitors. These different types of videos, such as 360-degree product videos, product demo videos, animated videos, and corporate videos. The Facebook study has demonstrated that users spend 3x more time watching live videos than normal videos. With the live video, you can get more user-created content.

Moreover, Instagram videos create around 3x more comments rather than Instagram photo posts. Instagram videos generally include short videos posted by real customers on Instagram with the tag of a particular brand. Brands can repost the stories as user-generated content to engage more audiences and create valid promotions on social media.

Similarly, imagine you are browsing a YouTube channel, and you look at a brand being supported by some authentic customers through a small video. So, it will catch your attention. With the videos, they can tell you about the branded products, especially the unboxing videos displaying all the inside products and how well it works for them. That type of video is enough to create a sense of desire in the consumers.

Continue Reading

#how to get more user generated content #importance of user generated content #user generated content #user generated content advantages #user generated content best practices #user generated content pros and cons