티스토리 뷰
Uncaught Error: Converting object to an encodable object failed: Instance of '{x}'
에러창꼬 2023. 3. 12. 16:06문제 발생
dart 언어에서는 jsonEncode 함수를 사용하여 객체를 간단하게 JSON 문자열로 변환할 수 있습니다.
Uncaught Error: Converting object to an encodable object failed: Instance of '{x}'
다만 사용하다 보면 위와 같은 에러가 발생하는 경우가 있는데요. (저 역시 최근에 겪음 ㅠ)
원인은 보통 두 가지입니다.
- 변환하고자 하는 객체에 toJson 구현 누락
- json의 데이터 타입은 기본적으로 string, number, object, array, boolean, null이 있으며 그 외에 타입을 변환하려는 경우
그럼 아래에서는 이 두 가지 케이스를 어떻게 해결해야 하는지 알아보겠습니다.
문제 해결
1. 변환하고자 하는 객체에 toJson 구현 누락
toJson이 누락된 경우 해결 방법은 간단합니다. class에 toJson을 구현해 주면 끝!
import 'dart:convert';
class Test {
final intType;
final strType;
Test(
int this.intType,
String this.strType
);
// toJson() 구현으로 해결
Map<String, dynamic> toJson() => {
'intType' : intType,
'strType' : strType
};
}
void main() {
String jsonStr = jsonEncode(Test(123, 'test'));
print(jsonStr); // {"intType":123,"strType":"test"}
}
2. json의 데이터 타입은 기본적으로 string, number, object, array, boolean, null이 있으며 그 외에 타입을 변환하려는 경우
타입 문제는 상황에 따라 달라집니다. 중요한 건 JSON의 데이터 타입이 string(""), number(숫자), object({}), array([]), boolean(true/false), null 이 존재한다는 것을 머릿속에 새기고 있어야 합니다. 예를 들어 객체의 변수 타입이 DateTime인 경우 JSON의 데이터 타입 중 하나로 변환을 해줘야 합니다. (아래 예제에서는 toString을 통하여 string 타입으로 변환했습니다)
import 'dart:convert';
class Test {
final intType;
final strType;
final dateType;
Test(
int this.intType,
String this.strType,
DateTime this.dateType
);
// toJson() 구현으로 해결
Map<String, dynamic> toJson() => {
'intType' : intType,
'strType' : strType,
'dateType' : dateType.toString()
};
}
void main() {
String jsonStr = jsonEncode(Test(123, 'test', DateTime.now()));
print(jsonStr); // {"intType":123,"strType":"test","dateType":"2023-03-12 15:55:19.558"}
}
toJson 부분을 보면 dateType에 toString()으로 JSON에서 다룰 수 있는 타입으로 변환하지 않으면 'Converting object to an encodable object failed' 에러가 발생합니다.
그리고 그 외에 num(int, double) 타입에서 NaN이나 Infinity 값이 있는 경우에도 에러가 발생하는데요. 이런 경우는 아래 포스팅에서 확인하실 수 있습니다.
Dart 언어의 int 타입에서 발생하는 Infinity
Infinity란? 오늘은 Dart 언어의 Infinity에 대해서 이야기해보려고 합니다. 일단 Dart 언어에서 Infinity의 정의에 대해 요즘 트렌드(?)에 맞춰서 ChatGPT에게 물어봤습니다. ChatGPT : Dart 언어에서 무한대(infi
error-storage.tistory.com
잘못된 내용이나 위에서 다룬 내용 외에 문제가 발생하는 케이스가 있으면 댓글 달아주시면 감사하겠습니다!
'모바일개발 > 플러터' 카테고리의 다른 글
Dart 언어의 int 타입에서 발생하는 Infinity (0) | 2023.03.11 |
---|---|
플러터 업그레이드 실패 : Your flutter checkout has local changes that would be erased by upgrading (0) | 2023.02.09 |