Orientação gerada a partir de informações públicas. Apenas para referência.
Typed_JSON é uma biblioteca Dart projetada para simplificar a serialização manual de JSON em projetos de qualquer escala. Ela fornece uma maneira limpa e segura por tipo para converter objetos Dart para e de JSON sem depender de reflexão ou informações de tipo em tempo de execução. Gerando código de serialização eficiente em tempo de compilação, ela garante desempenho e reduz o risco de erros em tempo de execução. A biblioteca se integra perfeitamente ao Flutter e a outras aplicações Dart, suportando todas as principais plataformas, incluindo Android, iOS, Web, macOS, Windows e Linux.
Casos de uso
Serialização manual de JSON em aplicativos em grande escala
Gerenciamento de modelo de dados seguro por tipo
Troca de dados entre plataformas
Reduzindo a dependência de tipos dinâmicos
Operações JSON críticas para desempenho
Lógica de serialização personalizada
Principais recursos
Geração de código em tempo de compilação
Sem reflexão em tempo de execução
Tipagem forte com pouco boilerplate
Suporte para tipos aninhados e complexos
Extensível por meio de serializadores personalizados
Leve e rápido
Indicado para
Desenvolvedores procurando controle total sobre a serialização JSON
Projetos que exigem alto desempenho e segurança de tipo
Equipes evitando dependência de mapeadores JSON de terceiros
Aplicações com modelos de dados complexos
Aplicativos Flutter que precisam de persistência de dados confiável
Considerações
Requer passo de geração de código
Curva de aprendizado para configuração de serializador personalizado
Limitado à lógica de serialização definida manualmente
Não ideal para estruturas de dados que mudam rapidamente
Pode aumentar levemente o tempo de compilação com muitos modelos
README original
Snapshot do README original do repositório-fonte vinculado. Consulte o repositório para o conteúdo mais recente.
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.