Simplifica a análise manual de JSON com uma API segura por tipo. Sem dynamic, sem conversão manual. Tipos de entrada flexíveis, tipos de saída fixos. Mensagens de erro úteis durante a análise
Orientação gerada a partir de informações públicas. Apenas para referência.
Deep Pick é um pacote Dart que simplifica a análise segura e com conhecimento de tipo de JSON, eliminando a necessidade de conversões manuais ou tipos dinâmicos. Ele fornece uma API limpa e expressiva para navegar em estruturas JSON aninhadas com mensagens de erro claras quando a análise falha. O pacote suporta tipos de entrada flexíveis, garantindo tipos de saída fixos e previsíveis, tornando-o ideal para lidar com dados JSON complexos ou profundamente aninhados de forma confiável em várias plataformas.
Casos de uso
Analisando respostas JSON profundamente aninhadas
Manipulação de campos JSON opcionais ou ausentes
Validando e extração de dados com segurança
Construindo clientes de API robustos
Trabalhando com JSON dinâmico de fontes externas
Reduzindo o código boilerplate na extração de modelo de dados
Principais recursos
Acesso JSON seguro por tipo
Mensagens de erro abrangentes
manipulação flexível de entrada
Sem dependência de 'dynamic'
Suporte para valores opcionais
Métodos encadeados para caminhos aninhados
Indicado para
Desenvolvedores trabalhando com APIs REST
Equipes que priorizam a segurança do código
Projetos que exigem análise confiável de JSON
Aplicativos com modelos de dados complexos
Desenvolvedores front-end usando Flutter
Quem evita erros em tempo de execução causados por conversões inválidas
Considerações
Requer compreensão da navegação baseada em caminho
Pode adicionar um pequeno sobrecusto para casos simples
Limitado a estruturas semelhantes ao JSON
Não adequado para formatos de dados não JSON
Melhor usado com esquemas de dados bem definidos
README original
Snapshot do README original do repositório-fonte vinculado. Consulte o repositório para o conteúdo mais recente.
deep_pick
Simplifies manual JSON parsing with a type-safe API.
This example demonstrates parsing of an HTTP response using deep_pick. You can either use it to parse individual values of a json response or parse whole objects using the fromPick constructor.
final response = await http.get(Uri.parse('https://api.countapi.xyz/stats'));
final json = jsonDecode(response.body);
// Parse individual fields (nullable)finalint? requests = pick(json, 'requests').asIntOrNull();
// Require values to be non-null or throw a useful error messagefinalint keys_created = pick(json, 'keys_created').asIntOrThrow();
// Pick deep nested values without parsing all objects in betweenfinalString? version = pick(json, 'meta', 'version', 'commit').asStringOrNull();
// Parse a full object using a fromPick factory constructorfinalCounterApiStats stats = CounterApiStats.fromPick(pick(json).required());
// Parse lists with a fromPick constructor finalList<CounterApiStats> multipleStats = pick(json, 'items')
.asListOrEmpty((pick) => CounterApiStats.fromPick(pick));
Returns the picked Object as String representation.
It doesn't matter if the value is actually a int, double, bool or any other Object.
pick calls the objects toString method.
pick tries to parse Strings with int.tryParse and double.tryParse.
A int can be parsed as double (no precision loss) but not vice versa because it could lead to mistakes.
Replacing the static function with a factory constructor doesn't work.
Constructors cannot be referenced as functions, yet (dart-lang/language/issues/216).
Meanwhile, use .asListOrEmpty((it) => Person.fromPick(it)) when using a factory constructor.
Note 2
pick called in the fromPick function uses the parameter pick, not the top-level function.
This is possible because Pick implements the .call() method.
This allows chaining indefinitely on the same Pick object while maintaining internal references for useful error messages.
Both versions produce the same result and shows you're not limited to 10 arguments.
Picking the Map is rarely used, because Pick itself grants further picking using the .call(args) method.
Converting back to a Map is usually only used for existing fromMap mapper functions.
Parsers in deep_pick are based on extension functions on the classes Pick.
This makes it flexible and easy for 3rd-party types to add custom parsers.
This example parses a int as Firestore Timestamp.
import'package:cloud_firestore/cloud_firestore.dart';
import'package:deep_pick/deep_pick.dart';
extensionTimestampPickonPick {
TimestampasFirestoreTimeStampOrThrow() {
final value = required().value;
if (value isTimestamp) {
return value;
}
if (value isint) {
returnTimestamp.fromMillisecondsSinceEpoch(value);
}
throwPickException("value $value at $debugParsingExit can't be casted to Timestamp");
}
Timestamp? asFirestoreTimeStampOrNull() {
if (value == null) returnnull;
try {
returnasFirestoreTimeStampOrThrow();
} catch (_) {
returnnull;
}
}
}
let
When using a custom type in only a few places, it might be overkill to create all the extensions.
For those cases use the let function borrowed from Kotlin to creating neat one-liners.
Picking values from a Firebase DocumentSnapshot is usually very selective.
Only a fraction of the properties have to be parsed.
In this scenario it would be overkill to map the whole document to a Dart object.
Instead, parse the values in place while staying type-safe.
Use .asStringOrThrow() when confident that the value is never null and always exists.
The return type then becomes non-nullable (String instead of String?).
When the data doesn't contain the full_name field (against your assumption) it would crash throwing a PickException.
finalDocumentSnapshot userDoc =
awaitFirebaseFirestore.instance.collection('users').doc(userId).get();
final data = userDoc.data();
finalString fullName = pick(data, 'full_name').asStringOrThrow();
finalString? level = pick(data, 'level').asIntOrNull();
deep_pick offers an alternative required() API with the same result.
This is useful to make sure a value exists before parsing it.
In case it is null or absent a useful error message is printed.
Before Dart 2.12 and the new ?[] operator one had to write a lot of code to prevent crashes when a value isn't set!
Reducing this boilerplate was the origin of deep_pick.
String milestoneCreator;
final milestone = json['milestore'];
if (milestone != null) {
final creator = json['creator'];
if (creator != null) {
final login = creator['login'];
if (login isString) {
milestoneCreator = login;
}
}
}
print(milestoneCreator); // octocat
This example of parses an issue object of the GitHub v3 API.
Today with Dart 2.12+ parsing Dart data structures has become way easier with the introduction of the ?[] operator.
final json = jsonDecode(response.data);
final milestoneCreator = json?['milestone']?['creator']?['login'] asString?;
print(milestoneCreator); // octocat
deep_pick backports this short syntax to previous Dart versions (<2.12).
final milestoneCreator = pick(json, 'milestone', 'creator', 'login').asStringOrNull();
print(milestoneCreator); // octocat
Still better than vanilla
But even with the latest Dart version, deep_pick offers fantastic features over vanilla parsing using the ?[] operators:
1. Flexible input types
Different languages and their JSON libraries generate different JSON.
Sometimes ids are String, sometimes int. Booleans are provided as true or with quotes as String "true".
The meaning is the same but from a type perspective they are not.
deep_pick does the basic conversions automatically.
By requesting a specific return type, apps won't break when a "price" usually returns double (0.99) but for whole numbers int (1 instead of 1.0).
Using the ?[] operator can crash for Lists.
Accessing a list item by index outside of the available range causes a RangeError.
You can't access index 23 when the List has only 10 items.
json['shoes']?[23]?['id'] asString?;
// Unhandled exception:// RangeError (index): Invalid value: Not in inclusive range 0..10: 23
pick automatically catches the RangeError and returns null.
Vanilla Dart returns a type error because null is not a String.
There is no information available which part is null or missing.
final milestoneCreator = json?['milestone']?['creator']?['login'] asString;
// Unhandled exception:// type 'Null' is not a subtype of type 'String' in type cast
deep_pick shows the exact location where parsing failed, making it easy to report errors to the API team.
final milestoneCreator = pick(json, 'milestone', 'creator', 'login').asStringOrThrow();
// Unhandled exception:// PickException(// Expected a non-null value but location "milestone" in pick(json, "milestone" (absent), "creator", "login") is absent. // Use asStringOrNull() when the value may be null at some point (String?).// )
Notice the distinction between "absent" and "null" when you see such errors.
"absent" means the key isn't found in a Map or a List has no item at the requested index
"null" means the value at that position is actually null
4. Null is default, crashes intentional
Parsing objects from external systems isn't type-safe.
API changes happen, and it is up to the consumer to decide how to handle them.
Consumer always have to assume the worst, such as missing values.
It's so easy to accidentally cast a value to String in the happy path, instead of String? accounting for all possible cases.
Easy to write, easy to miss in code reviews.
Forgetting that null could be a valid return type results in a type error:
json?['milestone']?['creator']?['login'] asString;
// ----^// Unhandled exception:// type 'Null' is not a subtype of type 'String' in type cast
With deep_pick, all casting methods (.as*()) have null in mind.
For each type you have to choose between at least two ways to deal with null.
Having "Throw" and "Null" in the method name, clearly indicates the possible outcome in case the values couldn't be picked.
Throwing is not a bad habit, some properties are essential for the business logic and throwing an error the correct handling.
But throwing should be done intentional, not accidental.
5. Map Objects with let
Even with the new ?[] operator, mapping a value to a new Object (i.e. when wrapping it in a domain Object) can't be done in a single line.
final value = json?['id'] asString?;
finalUserId id = value == null ? null : UserId(value);
deep_pick borrows the let function from Kotlin creating a neat one-liner
finalUserId id = pick(json, 'id').letOrNull((it) => UserId(it.asString()));
License
Copyright2019PascalWelschLicensed under the ApacheLicense, Version2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0Unlessrequired by applicable law or agreed to in writing, software
distributed under the Licenseis distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the Licensefor the specific language governing permissions and
limitations under the License.