Created
January 26, 2020 16:41
-
-
Save zmunk/1ac161a7ed9a797b376f817346758db4 to your computer and use it in GitHub Desktop.
Product to json string and back
This file contains hidden or 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'; | |
void main() { | |
final p = Product(name: 'gofret', price: '\$1.00', imgUrl: 'img.com'); | |
print(p); | |
print(p.runtimeType); | |
print(""); | |
final j = json.encode(p); | |
print(j); | |
print(j.runtimeType); | |
print(""); | |
final jmap = json.decode(j); | |
print(jmap); | |
print(jmap.runtimeType); | |
print(""); | |
final p2 = Product(name: jmap["name"], | |
price: jmap["price"], | |
imgUrl: jmap["imgUrl"]); | |
print(p2); | |
print(p2.runtimeType); | |
} | |
class Product { | |
String name; | |
String price; | |
String imgUrl; | |
Product({this.name, this.price, this.imgUrl}); | |
@override | |
String toString() { | |
return "Product : { name : $name, price: $price, imgUrl: $imgUrl }"; | |
} | |
@override | |
Map<String, dynamic> toJson() => { | |
"name": name == null ? null : name, | |
"price": price == null ? null : price, | |
"imgUrl": imgUrl == null ? null : imgUrl, | |
}; | |
factory Product.fromJson(String str) => Product.fromMap(json.decode(str)); | |
factory Product.fromMap(Map<String, dynamic> json) => Product( | |
name: json["name"] == null ? null : json["name"], | |
price: json["price"] == null ? null : json["price"], | |
imgUrl: json["imgUrl"] == null ? null : json["imgUrl"], | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment