skip to Main Content

if for example i had a map

{ 'id': 1, 'name': 'John' }

and I want to assign map values to class properties: Map keys are the properties and map values are the values for properties.

My Code :

class Person {
  late int id;
  late String name;

  Person.fromJson(Map<dynamic, dynamic> json) {
    // Solution 1
    id = json['id'];
    name = json['name'];

    // I want a better solution
    for (var key in json.keys) {
      print('${key} - ${json[key]}');
      // id - 1
      // name - John

      // this[key] = json[key]; ?
      // HOW CAN I DO THIS?
    }
  }
}

void main() {
  Person p = Person.fromJson({
    'id': 1,
    'name': 'John',
  });

  print('${p.id} - ${p.name}');
}
 ``

2

Answers


  1. You can use the factory constructors in this case, but first, you need to declare the class default constructor, so we will create an instance of that class constructor from the factory one, using the Map<String, dynamic>:

    // add this
    Person({
      required this.id,
      required this.name,
     });
    
    // then add this
    factory Person.fromJson(Map<dynamic, dynamic> json) {
      
      return Person(
         id: json['id'] as int,
         name: json['id'] as String,
       );
      }
    

    and now you can use the Person.fromJson() as you expect in your code:

     void main() {
      Person p = Person.fromJson({
        'id': 1,
        'name': 'John',
      });
    
      print('${p.id} - ${p.name}');
    }
    
    Login or Signup to reply.
  2. Manually writing out the toJson/fromJson methods is time consuming and not scalable. I would recommend using json_serializable and json_annotation.

    To do this, you simply create your class with the final properties you want and annotate it with @JsonSerializable()

    import 'package:json_annotation/json_annotation.dart';
    
    part 'person.g.dart';
    
    @JsonSerializable()
    class Person{
    
      final String name;
      final int id;
    
      Person({
        required this.name,
        required this.id,
    
    
      factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);
    
     Map<String, dynamic> toJson() => _$PersonToJson(this);
    }
    

    Then just run the build command and everything will be generated for you.

    flutter packages pub run build_runner build --delete-conflicting-outputs

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search