Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save AdnaneX/ca3278199b6f8817a89136f4b2cfcb4f to your computer and use it in GitHub Desktop.
Save AdnaneX/ca3278199b6f8817a89136f4b2cfcb4f to your computer and use it in GitHub Desktop.
import 'dart:convert';
class Restaurant {
Restaurant({
required this.name,
required this.cuisine,
this.yearOpened,
required this.reviews,
});
final String name;
final String cuisine;
final int? yearOpened;
final List<Review> reviews;
factory Restaurant.fromMap(Map<String, dynamic> data) {
final name = data['name'] as String;
final cuisine = data['cuisine'] as String;
final yearOpened = data['yearOpened'] as int?;
final reviewsData = data['reviews'] as List<dynamic>?;
final reviews = reviewsData != null
? reviewsData.map((reviewData) => Review.fromMap(reviewData)).toList()
: <Review>[];
return Restaurant(
name: name,
cuisine: cuisine,
yearOpened: yearOpened,
reviews: reviews,
);
}
Map<String, dynamic> toMap() {
return {
'name': name,
'cuisine': cuisine,
if (yearOpened != null) 'yearOpened': yearOpened,
'reviews': reviews.map((review) => review.toMap()).toList(),
};
}
}
class Review {
Review({required this.score, this.review});
final double score;
// nullable - assuming the review may be missing
final String? review;
factory Review.fromMap(Map<String, dynamic> data) {
final score = data['score'] as double;
final review = data['review'] as String?;
return Review(score: score, review: review);
}
Map<String, dynamic> toMap() {
return {
'score': score,
if (review != null) 'review': review,
};
}
}
void main() {
final jsonData =
'{"name":"Pizza da Mario","cuisine":"Italian","reviews":[{"score":4.5,"review":"The pizza was amazing!"},{"score":5.0,"review":"Very friendly staff, excellent service!"}]}';
final parsedJson = json.decode(jsonData);
final restaurant = Restaurant.fromMap(parsedJson);
final restaurantData = restaurant.toMap();
final encoded = json.encode(restaurantData);
assert(encoded == jsonData);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment