JSON to Dart
JSON से fromJson और toJson के साथ Dart क्लास जनरेट करें
JSON इनपुट
Dart आउटपुट
JSON से Dart रूपांतरण क्या है?
JSON से Dart रूपांतरण एक कच्चे JSON ऑब्जेक्ट को लेकर typed फ़ील्ड, एक नामित constructor, एक fromJson factory और एक toJson मेथड सहित Dart क्लास परिभाषाएँ तैयार करता है। Flutter में Dart के पास रनटाइम reflection नहीं होता (dart:mirrors अक्षम है), इसलिए स्पष्ट मैपिंग कोड लिखे बिना JSON को typed ऑब्जेक्ट में परिवर्तित नहीं किया जा सकता। प्रत्येक REST API प्रतिक्रिया, Firebase दस्तावेज़ या कॉन्फ़िगरेशन पेलोड के लिए एक संगत Dart मॉडल क्लास आवश्यक है — तभी आप उसके फ़ील्ड टाइप-सुरक्षित तरीके से उपयोग कर सकते हैं।
JSON के लिए एक सामान्य Dart मॉडल क्लास प्रत्येक कुंजी के लिए final फ़ील्ड, नामित पैरामीटर वाला एक constructor (non-nullable फ़ील्ड के लिए required कीवर्ड सहित), Map<String, dynamic> से पढ़ने वाला fromJson नामक एक factory constructor, और Map<String, dynamic> लौटाने वाला एक toJson मेथड घोषित करती है। नेस्टेड JSON ऑब्जेक्ट अलग-अलग क्लास बन जाते हैं। ऐरे typed List फ़ील्ड बन जाते हैं। Nullable JSON मान टाइप पर ? प्रत्यय के साथ Dart की null-safety syntax का उपयोग करते हैं।
ये मॉडल क्लास हाथ से लिखने का अर्थ है प्रत्येक JSON कुंजी पढ़ना, Dart प्रकार तय करना, प्रत्येक फ़ील्ड के लिए fromJson cast बनाना (.map().toList() के साथ सूची मैपिंग सहित), toJson map literal तैयार करना, और प्रत्येक नेस्टेड ऑब्जेक्ट के लिए यही दोहराना। 12 फ़ील्ड और 2 नेस्टेड ऑब्जेक्ट वाले JSON के लिए इसका अर्थ है 3 क्लास, 6 factory पंक्तियाँ और दर्जनों cast expressions। एक कनवर्टर यह सब एक पेस्ट से मिलीसेकंड में तैयार कर देता है।
JSON to Dart कनवर्टर का उपयोग क्यों करें?
JSON से Dart मॉडल क्लास हाथ से बनाने का अर्थ है फ़ील्ड नाम पढ़ना, नमूना मानों से प्रकार अनुमानित करना, सही null हैंडलिंग के साथ fromJson cast लिखना, और नेस्टेड ऑब्जेक्ट के लिए यही प्रक्रिया दोहराना। जब API response का structure बदले तो प्रत्येक फ़ील्ड अपडेट constructor, fromJson और toJson तीनों को छूता है। एक कनवर्टर यह दोहराव भरा काम समाप्त कर देता है।
JSON to Dart के use cases
JSON से Dart टाइप मैपिंग
प्रत्येक JSON मान एक विशिष्ट Dart प्रकार से संगत होता है। नीचे दी गई तालिका दर्शाती है कि कनवर्टर प्रत्येक JSON प्रकार को कैसे अनुवाद करता है। alternative column कम सामान्य या मैन्युअल मैपिंग परिदृश्यों में उपयोग किए जाने वाले प्रकार दर्शाता है।
| JSON प्रकार | उदाहरण | Dart प्रकार | विकल्प |
|---|---|---|---|
| string | "hello" | String | String |
| number (integer) | 42 | int | int |
| number (float) | 3.14 | double | double |
| boolean | true | bool | bool |
| null | null | dynamic | Null / dynamic |
| object | {"k": "v"} | NestedClass | Map<String, dynamic> |
| array of strings | ["a", "b"] | List<String> | List<String> |
| array of objects | [{"id": 1}] | List<Item> | List<Item> |
| mixed array | [1, "a"] | List<dynamic> | List<dynamic> |
Dart JSON Serialization के तरीके
Dart और Flutter JSON serialization संभालने के कई तरीके प्रदान करते हैं। मैन्युअल fromJson/toJson सबसे सरल तरीका है और किसी कोड जनरेशन की आवश्यकता नहीं। बड़े प्रोजेक्ट के लिए, build_runner आधारित समाधान जैसे json_serializable और freezed संकलन समय पर बॉयलरप्लेट जनरेट करते हैं, जिससे त्रुटियाँ कम होती हैं और मॉडल JSON अनुबंध के अनुरूप रहते हैं।
| तरीका | विवरण | स्रोत |
|---|---|---|
| json_serializable | Code-generation-based JSON serialization. Generates .g.dart files at build time via build_runner. Type-safe and compile-time verified. | Official (Google) |
| freezed | Generates immutable data classes with copyWith, fromJson/toJson, equality, and pattern matching support. Built on top of json_serializable. | Community (rrousselGit) |
| built_value | Generates immutable value types with serialization. Enforces immutability patterns. Used in larger codebases with strict data modeling. | |
| dart_mappable | Annotation-based mapper that generates fromJson, toJson, copyWith, and equality. Simpler setup than freezed with similar features. | Community |
| Manual fromJson/toJson | Hand-written factory constructors and toJson methods. No code generation needed. Full control over the mapping logic. | Built-in Dart |
Manual बनाम json_serializable बनाम freezed
Dart में JSON मॉडल क्लास के लिए तीन सामान्य तरीके हैं। मैन्युअल fromJson/toJson में कोई निर्भरता नहीं होती। json_serializable मैपिंग कोड स्वचालित करता है। freezed, json_serializable के ऊपर अपरिवर्तनीयता, copyWith और pattern matching जोड़ता है।
कोड उदाहरण
ये उदाहरण दर्शाते हैं कि JSON डीसीरियलाइज़ेशन के लिए जनरेटेड Dart क्लास का उपयोग कैसे करें, build_runner के साथ json_serializable कैसे सेट अप करें, और JavaScript तथा Python से प्रोग्रामेटिक रूप से Dart क्लास कैसे जनरेट करें।
import 'dart:convert';
class User {
final int id;
final String name;
final String email;
final bool active;
final Address address;
final List<String> tags;
User({
required this.id,
required this.name,
required this.email,
required this.active,
required this.address,
required this.tags,
});
factory User.fromJson(Map<String, dynamic> json) => User(
id: json['id'] as int,
name: json['name'] as String,
email: json['email'] as String,
active: json['active'] as bool,
address: Address.fromJson(json['address'] as Map<String, dynamic>),
tags: (json['tags'] as List<dynamic>).map((e) => e as String).toList(),
);
Map<String, dynamic> toJson() => {
'id': id,
'name': name,
'email': email,
'active': active,
'address': address.toJson(),
'tags': tags,
};
}
class Address {
final String street;
final String city;
final String zip;
Address({required this.street, required this.city, required this.zip});
factory Address.fromJson(Map<String, dynamic> json) => Address(
street: json['street'] as String,
city: json['city'] as String,
zip: json['zip'] as String,
);
Map<String, dynamic> toJson() => {'street': street, 'city': city, 'zip': zip};
}
void main() {
final jsonStr = '{"id":1,"name":"Alice","email":"alice@example.com","active":true,"address":{"street":"123 Main","city":"Springfield","zip":"12345"},"tags":["admin","user"]}';
final user = User.fromJson(jsonDecode(jsonStr));
print(user.name); // -> Alice
print(jsonEncode(user.toJson())); // -> round-trip back to JSON
}// pubspec.yaml dependencies:
// json_annotation: ^4.8.0
// dev_dependencies:
// build_runner: ^2.4.0
// json_serializable: ^6.7.0
import 'package:json_annotation/json_annotation.dart';
part 'user.g.dart'; // generated by: dart run build_runner build
@JsonSerializable()
class User {
final int id;
final String name;
final String email;
@JsonKey(name: 'is_active')
final bool isActive;
final List<String> tags;
User({
required this.id,
required this.name,
required this.email,
required this.isActive,
required this.tags,
});
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
Map<String, dynamic> toJson() => _$UserToJson(this);
}
// Run code generation:
// dart run build_runner build --delete-conflicting-outputsfunction jsonToDart(obj, name = "Root") {
const classes = [];
function infer(val, fieldName) {
if (val === null) return "dynamic";
if (typeof val === "string") return "String";
if (typeof val === "number") return Number.isInteger(val) ? "int" : "double";
if (typeof val === "boolean") return "bool";
if (Array.isArray(val)) {
const first = val.find(v => v !== null);
if (!first) return "List<dynamic>";
return `List<${infer(first, fieldName)}>`;
}
if (typeof val === "object") {
const cls = fieldName.charAt(0).toUpperCase() + fieldName.slice(1);
build(val, cls);
return cls;
}
return "dynamic";
}
function build(obj, cls) {
const fields = Object.entries(obj).map(([k, v]) =>
` final ${infer(v, k)} ${k};`
);
classes.push(`class ${cls} {\n${fields.join("\n")}\n}`);
}
build(obj, name);
return classes.join("\n\n");
}
console.log(jsonToDart({ id: 1, name: "Alice", scores: [98, 85] }, "User"));
// class User {
// final int id;
// final String name;
// final List<int> scores;
// }import json
def json_to_dart(obj: dict, class_name: str = "Root") -> str:
classes = []
def infer(val, name):
if val is None:
return "dynamic"
if isinstance(val, bool):
return "bool"
if isinstance(val, int):
return "int"
if isinstance(val, float):
return "double"
if isinstance(val, str):
return "String"
if isinstance(val, list):
if not val:
return "List<dynamic>"
return f"List<{infer(val[0], name)}>"
if isinstance(val, dict):
cls = name[0].upper() + name[1:]
build(val, cls)
return cls
return "dynamic"
def build(obj, cls):
fields = [f" final {infer(v, k)} {k};" for k, v in obj.items()]
classes.append(f"class {cls} {{\n" + "\n".join(fields) + "\n}")
build(obj, class_name)
return "\n\n".join(classes)
data = json.loads('{"id": 1, "name": "Alice", "active": true}')
print(json_to_dart(data, "User"))
# class User {
# final int id;
# final String name;
# final bool active;
# }