Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.1 kB
4
Indexable
Never
import 'dart:convert';

void main() {
  final jsonString = '''
  {
    "person1": {
      "name": "John",
      "age": 30,
      "email": "john@example.com"
    },
    "person2": {
      "name": "Jane",
      "age": 25,
      "email": "jane@example.com"
    }
  }
  ''';

  final parsedJson = jsonDecode(jsonString);

  final dynamicData = DynamicData.fromJson(parsedJson);

  print(dynamicData.person1.name); // John
  print(dynamicData.person2.age); // 25
}

class DynamicData {
  final Map<String, Person> persons;

  DynamicData({required this.persons});

  factory DynamicData.fromJson(Map<String, dynamic> json) {
    final persons = <String, Person>{};

    for (final entry in json.entries) {
      persons[entry.key] = Person.fromJson(entry.value);
    }

    return DynamicData(persons: persons);
  }
}

class Person {
  final String name;
  final int age;
  final String email;

  Person({required this.name, required this.age, required this.email});

  factory Person.fromJson(Map<String, dynamic> json) {
    return Person(
      name: json['name'],
      age: json['age'],
      email: json['email'],
    );
  }
}