'Flutter JSON response to generic error model
I'm using a Laravel API with Laravel form validation. Is there a best practice to convert the Laravel API response to an error model?
{
"message": "The given data was invalid.",
"errors": {
"email": [
"E-mailadres is taken."
],
"username": [
"Username is taken."
],
"first_name": [
"Firstname is required."
]
}
}
Can anyone help me to write an ErrorResponse class to convert the JSON response to a model? The keys email, username, first_name can be different, so they must be dynamic.
Solution 1:[1]
class ErrorMessage {
String message;
ErrorMessage({this.message});
static List<ErrorMessage> fromJson(Map<String, dynamic> json) {
final errorMessages = List<ErrorMessage>();
for (final item in json) {
errorMessages.add(ErrorMessage(
message: item[0]));
}
return errorMessages;
}
}
Solution 2:[2]
You can easliy do this using flutter factory method Do like this:-
class ErrorResponse{
String message;
Map<String,String> errors;
ErrorResponse({
this.message,
this.errors,
});
factory ErrorResponse.fromJson(Map<String,dynamic> json){
return ErrorResponse(
message: json['message'],
errors : json['errors'], //you may have to use json.decode here
);
}
}
Then just do ErrorResponse err = ErrorResponse.fromJson(jsonResponse);
This is just a pseudo code and may contains errors but this is the way you do it in flutter.
Also you may have to do some operation like decoding the error json using json.decode to decode it in Map.
Solution 3:[3]
class ErrorResponse {
String? message;
ErrorResponse({this.message});
static ErrorResponse fromJson(Map<String, dynamic> json) {
final errorMessages = <ErrorResponse>[];
json.forEach((key, value) {
if (key == "errors") {
Map<String, dynamic> map = Map<String, dynamic>.from(json[key]);
map.forEach((mapKey, value) {
errorMessages.add(ErrorResponse(message: map[mapKey][0]));
});
}
});
return errorMessages.first;
}
}
This worked for me
after that for convert massage
ErrorRespons = ErrorResponse.fromJson(jsonDecode(responded.body));
then you can use error.massage
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Muhideen Mujeeb Adeoye |
| Solution 2 | Abhay Kumar |
| Solution 3 | Abhishek Yadav |
