Last active
September 24, 2023 15:03
-
-
Save ramanraja/c6ecc51be5ad1d5b9ec7b8674acdb11e to your computer and use it in GitHub Desktop.
Example of converting from/to a custom Dart class to JSON
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
// Conversion from/to JSON to String in Dart | |
// Also simple DIY conversion to a custom class object | |
import 'dart:convert'; | |
class dto{ | |
String name; | |
int age; | |
dto(this.name, this.age); | |
factory dto.fromJson(Map<String, dynamic>? jmap) { | |
if(jmap == null) throw FormatException('Input is NULL!'); | |
return dto(jmap['name'], jmap['age']); | |
} | |
@override | |
String toString(){ | |
return('Your name is $name and you are $age years old.'); | |
} | |
Map<String, dynamic> toJson(){ | |
Map<String, dynamic> retval = {}; | |
retval['name'] = name; | |
retval['age'] = age; | |
return (retval); | |
} | |
} | |
void main() { | |
String jstr = '{"name":"Randy","age":44}'; | |
dynamic jmap = jsonDecode (jstr); | |
print(jmap['name']); | |
print(jmap['age']); | |
jmap['name'] = 'Appu'; | |
jmap['age'] = 33; | |
print(jmap); | |
String newstr = jsonEncode(jmap); | |
print(newstr); | |
dto mydto = dto.fromJson(jmap); | |
print(mydto); | |
Map<String, dynamic> jdto = mydto.toJson(); | |
print(jdto); | |
Map<String, dynamic>? jm; | |
try { | |
dto mydto2 = dto.fromJson(jm); | |
} | |
on FormatException catch(e) { | |
print ('conversion failed:'); | |
print (e.toString()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment