dart map to json code example

Example 1: flutter access json object inside object

myJson = {
  "label": "This is a string",
  "value": {
  	"address": "This is a string",
    "country": "This is a string"
  }
}

//to access address field
var decodedJson = json.decode(myJson);
var jsonValue = json.decode(decodedJson['value']);
print(jsonValue['address']);

Example 2: dart map to json string

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

Example 3: dart object to map

class Human {
  String name;
  int age;

  Map<String, dynamic> toMap() {
    return {
      'name': name,
      'age': age,
    };
  }
}

Tags:

Misc Example