0

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 2

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}');
}
Sign up to request clarification or add additional context in comments.

1 Comment

this is not what i want , i want to remove id = json['id']; name = json['name']; i want instance automatically take all json entries as properties `
1

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

2 Comments

what about creating a superclass with a fromJson method which automatically add all JSON key & values as attributes ... this is what I want to do here
@d3ridi There currently is no automatic way to generate objects from Maps in Dart. Using code generation (such as using package:json_serializable or package:built_value) is the proper thing to do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.