Created
August 5, 2021 11:51
-
-
Save bizz84/798c1c5a69690af54d09ca6e8469faec to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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