Created
November 10, 2024 02:10
-
-
Save bsutton/816c5558280c5c0c68bdf1f09bb76467 to your computer and use it in GitHub Desktop.
json decode
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
I think your basic approach is flawed. You should be decoding it as a json object. | |
I've not tested this but it looks about right - chat gpt generated by asking 'change this code to decode it into a class' | |
```dart | |
void main() async { | |
try { | |
var response = await http.post( | |
Uri.parse(AppSecrecy.CharacterCreatemysql), | |
headers: {"Content-Type": "application/json"}, | |
body: jsonEncode(regBody1), | |
); | |
if (response.statusCode == 200) { | |
// Decode the response body JSON into the Character class | |
var character = Character.fromJson(jsonDecode(response.body)); | |
// Print out properties to verify decoding | |
print('Character CUID: ${character.cuid}'); | |
print('Character Name: ${character.name}'); | |
print('Character Sex: ${character.sex}'); | |
print('Character Alive: ${character.alive}'); | |
print('Character Age: ${character.age}'); | |
} else { | |
print('Failed to load character data: ${response.statusCode}'); | |
} | |
} catch (e) { | |
print('Error: $e'); | |
} | |
} | |
class Character { | |
final String cuid; | |
final String name; | |
final String sex; | |
final bool alive; | |
final int age; | |
Character({ | |
required this.cuid, | |
required this.name, | |
required this.sex, | |
required this.alive, | |
required this.age, | |
}); | |
// Factory constructor to create a Character instance from JSON | |
factory Character.fromJson(Map<String, dynamic> json) { | |
return Character( | |
cuid: json['cuid'], | |
name: json['name'], | |
sex: json['sex'], | |
alive: json['alive'], | |
age: json['age'], | |
); | |
} | |
// Method to convert a Character instance to JSON (if needed for other requests) | |
Map<String, dynamic> toJson() { | |
return { | |
'cuid': cuid, | |
'name': name, | |
'sex': sex, | |
'alive': alive, | |
'age': age, | |
}; | |
} | |
} | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment