dart object to json code example

Example 1: dart map to json string

import 'dart:convert';
...
json.encode(data); // JSON.encode(data) in Dart 1.x

Example 2: flutter generate json files

flutter packages pub run build_runner build

Example 3: parse json to dart model

import 'dart:convert';

main() {
  String nestedObjText =
      '{"title": "Dart Tutorial", "description": "Way to parse Json", "author": {"name": "bezkoder", "age": 30}}';

  Tutorial tutorial = Tutorial.fromJson(jsonDecode(nestedObjText));

  print(tutorial);

Example 4: json to dart

class Autogenerated {
  int postId;
  int id;
  String name;
  String email;
  String body;

  Autogenerated({this.postId, this.id, this.name, this.email, this.body});

  Autogenerated.fromJson(Map<String, dynamic> json) {
    postId = json['postId'];
    id = json['id'];
    name = json['name'];
    email = json['email'];
    body = json['body'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['postId'] = this.postId;
    data['id'] = this.id;
    data['name'] = this.name;
    data['email'] = this.email;
    data['body'] = this.body;
    return data;
  }
}

Example 5: flutter json to class

//insideclass
ClassName.fromJson(Map<String, dynamic> json) {
    variable1 = json['variable11'];
    variable2 = json['variable12'];
    variable3 = json['variable13']['variable14'];
}

//uses
//after http request or whatever
Map<dynamic, dynamic> res = await jsonDecode(response.body.toString());
Classname.fromJson(res);

Example 6: convert json to dart

class Todo {
  int userId;
  int id;
  String title;
  bool completed;

  Todo({this.userId, this.id, this.title, this.completed});

  Todo.fromJson(Map<String, dynamic> json) {
    userId = json['userId'];
    id = json['id'];
    title = json['title'];
    completed = json['completed'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['userId'] = this.userId;
    data['id'] = this.id;
    data['title'] = this.title;
    data['completed'] = this.completed;
    return data;
  }
}

Tags:

Misc Example