Home > database >  Could someone tell me if im right about what these parts of the code do
Could someone tell me if im right about what these parts of the code do

Time:11-06

Could someone tell me if im right about what these parts of the code do:

This is JSON to string conversion?

factory Post.fromJson(Map<String, dynamic> json) => Post(
    userId: json["userId"],
    id: json["id"],
    title: json["title"],
    body: json["body"],
  );

And this would be string to JSON conversion?

Map<String, dynamic> toJson() => {
    "userId": userId,
    "id": id,
    "title": title,
    "body": body,
  };

CodePudding user response:

In Dart, Json equivalent type is Map. The first fromJson() method is converting Map to a Post model class which is custom defined.

Your Post model class will look like this.

Post{
final int userId;
final int id;
final String title;
final String body;

Post({required this.userId,required this.id,required this.title,required this.body});
}

Using raw Map data type is handy and dangerous. You have to memorize all key names. So, you first convert json response to Map and then Map to Post model class. That's what fromJson does. The process is as follows.

///Converts Json to Map
Map<String,dynamic> mapData = jsonDecode(json);

///Converts Map to Post class
Post post = Post.fromJson(mapData);

toJson() method is reverse of fromJson(). It converts Post class to Map data type. And then you convert it to Json for api requests. The process is like this.

/// Conoverts Post class to Map
Map<String,dynamic> mapData = post.toJson();

///Converts Map to Json
String json = jsonEncode(mapData);

Have fun :)

CodePudding user response:

yes, it's totally true, the fromJson factory will create the Post class instance from a JSON Map. and the to toJson will return a JSON Map to use it.

it's totally right

  • Related