Typed_JSON은 어떤 규모의 프로젝트에서도 수동 JSON 직렬화를 간소화하도록 설계된 Dart 라이브러리입니다. 반사(reflection)이나 런타임 타입 정보에 의존하지 않고 Dart 객체를 JSON으로, 그리고 JSON을 Dart 객체로 변환하는 깔끔하고 타입 안전한 방법을 제공합니다. 컴파일 시점에 효율적인 직렬화 코드를 생성함으로써 성능을 보장하고 런타임 오류의 위험을 줄입니다. 이 라이브러리는 Flutter 및 기타 Dart 애플리케이션에 원활하게 통합되며 Android, iOS, Web, macOS, Windows, Linux 등 주요 플랫폼을 모두 지원합니다.
사용 사례
대규모 앱에서의 수동 JSON 직렬화
형 안전한 데이터 모델 처리
크로스 플랫폼 데이터 교환
동적 유형에 대한 의존도 감소
성능 중심의 JSON 작업
사용자 정의 직렬화 로직
주요 기능
컴파일 시 코드 생성
런타임 반사 없음
최소한의 보일러플레이트를 갖춘 강력한 타입 시스템
중첩 및 복잡한 형식 지원
사용자 정의 시리얼라이저를 통해 확장 가능
경량이고 빠름
적합한 대상
JSON 직렬화에 대한 완전한 제어를 원하는 개발자
고성능과 타입 안전성이 필요한 프로젝트
제3자 JSON 매핑기 의존을 피하는 팀
복잡한 데이터 모델을 가진 응용 프로그램
신뢰할 수 있는 데이터 지속성을 필요로 하는 플러터 앱
고려 사항
코드 생성 단계가 필요합니다
사용자 정의 시리얼라이저 설정의 학습 곡선
수동으로 정의된 직렬화 로직에 제한됨
빠르게 변화하는 데이터 구조에는 적합하지 않음
모델이 많을 경우 빌드 시간이 약간 증가할 수 있습니다
원본 README
연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.
Typed JSON
A library intended to bring manual JSON serialization to the Dart projects of all scales.
Features:
Human readable and maintainable API
Strict compile-time and runtime types checks
Nested objects parsing
Lists of objects parsing
Exceptions that include a JSON key path with an error
try {
int? intVal = json["year"].intValue;
String? stringVal = json["title"].stringValue;
double? doubleVal = json["price"].doubleValue;
num? numValue = json["price"].numValue;
bool? boolVal = json["inStock"].boolValue;
} onJsonValueExceptioncatch (e) {
print(e.value) // The value of the faulty fieldprint(e) // "Unable to parse the value at the/path/to/field"...
}
In this case, the JsonValueException will be thrown if the type of the value is incorrect. The null value is permitted.
Required values
If the value must not be null, you can use the *OrException properties:
try {
int intVal = json["year"].intOrException;
String stringVal = json["title"].stringOrException;
double doubleVal = json["price"].doubleOrException;
num numValue = json["price"].numOrException;
bool boolVal = json["inStock"].boolOrException;
} onJsonValueExceptioncatch (e) {
print(e.value) // The value of the faulty fieldprint(e) // "Unable to parse the required value at the/path/to/field"...
}
In this case, the JsonValueException will be thrown if the type of the value is incorrect or the value is null.
In the example above the keys "root" and "nested" must not be null, otherwise the JsonException will be thrown.
If you need to parse the nested JSON with keys that can be null, you should check it explicitly.
final value = j["inexisted"].optional["nested"].stringValue; // null
In the example, we marked the path "inexisted" as optional. The JSON parser will know that the "inexisted" can be null. And the "nested" and all the keys to the right side of "inexisted" can be null as well.
Null checks
You can check if the JSON value is not null:
final json = Json.empty(); // json with nullprint(json != null) // trueprint(json.isExist) // false
You can check if the JSON object contains the element with the giving name:
final json = Json.object(); // json with {}print(json.isExist) // trueprint(json["key"].isExist) // false
Now you can work with JSON values of the custom type using the get and set methods.
final valueJson = Json.empty();
valueJson.set(Status.active, StatusAdapter());
Status? valueStatus = valueJson.get(StatusAdapter());
final objectJson = Json.object();
objectJson["key"].set(Status.active, StatusAdapter());
Status? ojectStatus = objectJson["key"].get(StatusAdapter());
If the value must not be null, you can use the getRequired method.
final valueJson = Json.empty();
valueJson.set(Status.active, StatusAdapter());
Status valueStatus = valueJson.getRequired(StatusAdapter());
If the custom adapter returns null, the getRequired method will throw a JsonValueException.
try {
Json("incorrect").getRequired(StatusAdapter());
} onJsonValueExceptioncatch (e) {
print(e.value) // The value of the faulty fieldprint(e) // "Unable to parse the required value at the/path/to/field"...
}
Authors
Evgeniy Safronov (evsafronov.personal@gmail.com)
Alexander Smetannikov (alexsmetdev@gmail.com)
License
Typed JSON is available under the MIT license. See the LICENSE file for more info.