JSON to Dart

JSON से fromJson और toJson के साथ Dart क्लास जनरेट करें

उदाहरण देखें
रूट क्लास का नाम:

JSON इनपुट

Dart आउटपुट

स्थानीय रूप से चलता है · सीक्रेट पेस्ट करना सुरक्षित है
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 तीनों को छूता है। एक कनवर्टर यह दोहराव भरा काम समाप्त कर देता है।

Instant क्लास जनरेशन
JSON चिपकाएँ और एक सेकंड से कम समय में constructor, fromJson factory और toJson मेथड सहित संपूर्ण Dart क्लास पाएँ। नेस्टेड ऑब्जेक्ट और सूचियाँ स्वतः पहचानी और संगत की जाती हैं।
🔒
Data पूरी तरह निजी
रूपांतरण पूरी तरह आपके ब्राउज़र में JavaScript के माध्यम से चलता है। आपका JSON डेटा कभी आपकी मशीन से बाहर नहीं जाता। API कुंजियाँ, टोकन और उत्पादन पेलोड निजी रहते हैं।
📝
Null-safe आउटपुट
जनरेटेड क्लास Dart की sound null safety का उपयोग करती हैं। Nullable JSON फ़ील्ड को ? टाइप प्रत्यय मिलता है और constructor में required कीवर्ड छोड़ दिया जाता है। Non-null फ़ील्ड required चिह्नित होती हैं।
📦
इंस्टॉलेशन या साइनअप ज़रूरी नहीं
पेज खोलें और JSON चिपकाएँ। Dart SDK की आवश्यकता नहीं, pub निर्भरताओं की आवश्यकता नहीं, खाते की आवश्यकता नहीं। ब्राउज़र वाले किसी भी उपकरण पर काम करता है।

JSON to Dart के use cases

Flutter ऐप विकास
http या dio पैकेज द्वारा उपयोग की जाने वाली REST API प्रतिक्रियाओं के लिए मॉडल क्लास जनरेट करें। अपने बैकएंड द्वारा लौटाया गया JSON चिपकाएँ और jsonDecode तथा विजेट रेंडरिंग के लिए तैयार Dart क्लास पाएँ।
Firebase / Firestore एकीकरण
Firestore दस्तावेज़ स्नैपशॉट के लिए typed मॉडल क्लास बनाएँ। नमूना दस्तावेज़ JSON के रूप में चिपकाएँ, Dart क्लास जनरेट करें, और अपनी repository परत में snapshot.data() के साथ fromJson का उपयोग करें।
State Management मॉडल
Riverpod, Bloc या Provider के लिए typed state ऑब्जेक्ट परिभाषित करें। अपेक्षित state आकार JSON के रूप में चिपकाएँ और state की दृढ़ता व हाइड्रेशन के लिए toJson के साथ अपरिवर्तनीय Dart क्लास पाएँ।
API Client कोड जनरेशन
Retrofit या Chopper API क्लाइंट के लिए request और response मॉडल तैयार करें। नमूना JSON पेलोड चिपकाएँ और अपने OpenAPI response schema से संगत Dart क्लास पाएँ।
स्वचालित परीक्षण
वास्तविक API प्रतिक्रियाओं से typed परीक्षण फ़िक्सचर बनाएँ। JSON नमूना चिपकाएँ, मॉडल क्लास जनरेट करें, और fixture संरचनाएँ हाथ से लिखे बिना सीधे unit और widget परीक्षणों में उपयोग करें।
Dart पैटर्न सीखना
Flutter सीखने वाले छात्र कोई भी JSON संरचना चिपकाकर देख सकते हैं कि Dart उसे कैसे दर्शाता है: final फ़ील्ड, नामित constructor, factory fromJson पैटर्न, और व्यवहार में null-safety एनोटेशन।

JSON से Dart टाइप मैपिंग

प्रत्येक JSON मान एक विशिष्ट Dart प्रकार से संगत होता है। नीचे दी गई तालिका दर्शाती है कि कनवर्टर प्रत्येक JSON प्रकार को कैसे अनुवाद करता है। alternative column कम सामान्य या मैन्युअल मैपिंग परिदृश्यों में उपयोग किए जाने वाले प्रकार दर्शाता है।

JSON प्रकारउदाहरणDart प्रकारविकल्प
string"hello"StringString
number (integer)42intint
number (float)3.14doubledouble
booleantrueboolbool
nullnulldynamicNull / dynamic
object{"k": "v"}NestedClassMap<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_serializableCode-generation-based JSON serialization. Generates .g.dart files at build time via build_runner. Type-safe and compile-time verified.Official (Google)
freezedGenerates immutable data classes with copyWith, fromJson/toJson, equality, and pattern matching support. Built on top of json_serializable.Community (rrousselGit)
built_valueGenerates immutable value types with serialization. Enforces immutability patterns. Used in larger codebases with strict data modeling.Google
dart_mappableAnnotation-based mapper that generates fromJson, toJson, copyWith, and equality. Simpler setup than freezed with similar features.Community
Manual fromJson/toJsonHand-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 जोड़ता है।

Manual fromJson/toJson
fromJson factory और toJson मेथड हाथ से लिखें। कोई निर्भरता नहीं, कोई build_runner चरण नहीं। cast logic और त्रुटि हैंडलिंग पर पूर्ण नियंत्रण। कुछ मॉडल वाले छोटे प्रोजेक्ट के लिए, या जब कोड जनरेटर द्वारा व्यक्त न हो सकने वाले कस्टम डीसीरियलाइज़ेशन की आवश्यकता हो, तो सर्वोत्तम। यही इस टूल का आउटपुट स्वरूप है।
json_serializable
अपनी क्लास को @JsonSerializable() से एनोटेट करें और dart run build_runner build चलाएँ। जनरेटर _$ClassFromJson और _$ClassToJson फ़ंक्शन के साथ एक .g.dart फ़ाइल बनाता है। फ़ील्ड नाम बदलने, डिफ़ॉल्ट मान और कस्टम कनवर्टर के लिए @JsonKey संभालता है। मध्यम से बड़े Flutter प्रोजेक्ट के लिए मानक विकल्प।
freezed
@freezed से एनोटेट करें और fromJson, toJson, copyWith, समता (== और hashCode), और toString स्वतः जनरेट होने वाली अपरिवर्तनीय क्लास पाएँ। sealed class पैटर्न के लिए union प्रकार समर्थित हैं। dev निर्भरताओं के रूप में freezed और json_serializable दोनों आवश्यक हैं। state management मॉडल और जटिल domain ऑब्जेक्ट के लिए सर्वोत्तम।

कोड उदाहरण

ये उदाहरण दर्शाते हैं कि JSON डीसीरियलाइज़ेशन के लिए जनरेटेड Dart क्लास का उपयोग कैसे करें, build_runner के साथ json_serializable कैसे सेट अप करें, और JavaScript तथा Python से प्रोग्रामेटिक रूप से Dart क्लास कैसे जनरेट करें।

Dart (manual fromJson / toJson)
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
}
Dart (json_serializable + build_runner)
// 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-outputs
JavaScript (generate Dart classes from JSON)
function 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;
// }
Python (generate Dart model from JSON)
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;
# }

अक्सर पूछे जाने वाले प्रश्न

Flutter JSON डीसीरियलाइज़ेशन के लिए dart:mirrors का उपयोग क्यों नहीं कर सकता?
Flutter dart:mirrors (reflection लाइब्रेरी) अक्षम करता है क्योंकि tree-shaking के लिए संकलन समय पर यह जानना आवश्यक है कि कौन-सा कोड उपयोग होता है। Reflection संकलक को अप्रयुक्त क्लास हटाने से रोकेगी, जिससे ऐप का आकार बढ़ेगा। इसीलिए Flutter प्रोजेक्ट को रनटाइम reflection की बजाय स्पष्ट fromJson/toJson मेथड या कोड जनरेशन की आवश्यकता होती है।
क्या json_serializable उपयोग करनी चाहिए या fromJson हाथ से लिखनी चाहिए?
10 से कम मॉडल क्लास वाले प्रोजेक्ट के लिए, हाथ से लिखी fromJson/toJson सरल है और कोई build निर्भरता नहीं जोड़ती। जब 10 से अधिक मॉडल हों, या मॉडल बार-बार बदलते हों, तो json_serializable समय बचाती है और copy-paste त्रुटियाँ कम करती है। यह एनोटेशन से मैपिंग कोड जनरेट करती है, इसलिए फ़ील्ड जोड़ने पर केवल build_runner पुनः चलाना होता है।
कनवर्टर नेस्टेड JSON ऑब्जेक्ट को कैसे संभालता है?
प्रत्येक नेस्टेड JSON ऑब्जेक्ट एक अलग Dart क्लास बन जाता है। यदि "address" नामक JSON फ़ील्ड में "street" और "city" कुंजियों वाला ऑब्जेक्ट है, तो कनवर्टर उन फ़ील्ड के साथ एक Address क्लास बनाता है और मूल फ़ील्ड का प्रकार Address निर्धारित करता है। fromJson factory नेस्टेड map को cast करती है और उसे Address.fromJson को भेजती है।
JSON फ़ील्ड null होने पर क्या होता है?
Null फ़ील्ड ? प्रत्यय के साथ dynamic टाइप की होती हैं क्योंकि कनवर्टर केवल null मान से अपेक्षित प्रकार निर्धारित नहीं कर सकता। जब API अनुबंध से प्रकार ज्ञात हो तो dynamic? को सही प्रकार (String?, int? आदि) से बदलें। Dart की null safety तब संकलन समय पर सही null जाँच लागू करेगी।
वैध Dart पहचानकर्ता न होने वाली JSON कुंजियाँ कैसे संभालें?
"first-name" या "2nd_place" जैसी JSON कुंजियाँ वैध Dart फ़ील्ड नाम नहीं हैं। मैन्युअल fromJson के साथ, factory constructor में किसी भी JSON कुंजी को किसी भी Dart फ़ील्ड नाम से संगत किया जा सकता है। json_serializable के साथ, फ़ील्ड एनोटेट करने के लिए @JsonKey(name: 'first-name') का उपयोग करें। कनवर्टर स्वतः कुंजी नामों को camelCase Dart फ़ील्ड में बदलता है।
क्या इस टूल के आउटपुट के साथ freezed उपयोग कर सकते हैं?
यह टूल मैन्युअल fromJson/toJson के साथ मानक Dart क्लास जनरेट करता है। freezed में बदलने के लिए, क्लास में @freezed एनोटेशन जोड़ें, हाथ से लिखे constructor और factory हटाएँ, और freezed mixin जोड़ें। फिर .freezed.dart और .g.dart फ़ाइलें जनरेट करने के लिए build_runner चलाएँ। जनरेटेड आउटपुट के फ़ील्ड नाम और प्रकार सीधे स्थानांतरित होते हैं।
JSON के लिए कच्चे map और typed Dart क्लास में क्या अंतर है?
कच्चा map (Map<String, dynamic>) बिना किसी टाइप जाँच के JSON डेटा तक सीधी पहुँच देता है। आपको call site पर प्रत्येक मान cast करना होता है, और कुंजी नामों में टाइपिंग गलतियाँ रनटाइम पर चुपचाप विफल होती हैं। typed Dart क्लास fromJson सीमा पर टाइप असंगति पकड़ती है, फ़ील्ड नामों के लिए IDE स्वतः-पूर्णता प्रदान करती है, और refactoring को सुरक्षित बनाती है। प्रदर्शन अंतर नगण्य है; लाभ पूरी तरह शुद्धता और maintainability के बारे में है।