All tools
Free
flutter

JSON → Dart Model

Konversi JSON ke Dart class dengan fromJson & toJson otomatis.

JSON → Dart Model
Paste valid JSON, atur opsi, lalu copy/download class Dart hasilnya.
class Model {
  final int? id;
  final String? name;
  final bool? isActive;
  final double? rating;
  final List<String>? tags;
  final Address? address;
  final List<Item>? items;

  const Model({
    this.id,
    this.name,
    this.isActive,
    this.rating,
    this.tags,
    this.address,
    this.items,
  });

  factory Model.fromJson(Map<String, dynamic> json) => Model(
    id: (json['id'] as num?)?.toInt(),
    name: json['name'] as String?,
    isActive: json['isActive'] as bool?,
    rating: (json['rating'] as num?)?.toDouble(),
    tags: (json['tags'] as List?)?.map((e) => e as String).toList(),
    address: json['address'] == null ? null : Address.fromJson(json['address'] as Map<String, dynamic>),
    items: (json['items'] as List?)?.map((e) => Item.fromJson(e as Map<String, dynamic>)).toList(),
  );

  Map<String, dynamic> toJson() => {
    'id': id,
    'name': name,
    'isActive': isActive,
    'rating': rating,
    'tags': tags,
    'address': address?.toJson(),
    'items': items?.map((e) => e.toJson()).toList(),
  };

  Model copyWith({
    int? id,
    String? name,
    bool? isActive,
    double? rating,
    List<String>? tags,
    Address? address,
    List<Item>? items,
  }) => Model(
    id: id ?? this.id,
    name: name ?? this.name,
    isActive: isActive ?? this.isActive,
    rating: rating ?? this.rating,
    tags: tags ?? this.tags,
    address: address ?? this.address,
    items: items ?? this.items,
  );
}

class Address {
  final String? city;
  final String? zip;

  const Address({
    this.city,
    this.zip,
  });

  factory Address.fromJson(Map<String, dynamic> json) => Address(
    city: json['city'] as String?,
    zip: json['zip'] as String?,
  );

  Map<String, dynamic> toJson() => {
    'city': city,
    'zip': zip,
  };

  Address copyWith({
    String? city,
    String? zip,
  }) => Address(
    city: city ?? this.city,
    zip: zip ?? this.zip,
  );
}

class Item {
  final String? sku;
  final num? price;
  final double? discount;

  const Item({
    this.sku,
    this.price,
    this.discount,
  });

  factory Item.fromJson(Map<String, dynamic> json) => Item(
    sku: json['sku'] as String?,
    price: (json['price'] as num?),
    discount: (json['discount'] as num?)?.toDouble(),
  );

  Map<String, dynamic> toJson() => {
    'sku': sku,
    'price': price,
    'discount': discount,
  };

  Item copyWith({
    String? sku,
    num? price,
    double? discount,
  }) => Item(
    sku: sku ?? this.sku,
    price: price ?? this.price,
    discount: discount ?? this.discount,
  );
}

Butuh bantuan dengan project Anda? Hubungi saya.