All 7 JSON Serialization & Deserialization questions
More in JSON Serialization & Deserialization
Advertisement
Back to results for “Set”
Flutter › JSON Serialization & Deserialization

How do you properly handle deserializing a genuinely nested JSON structure, such as an order object that itself contains an embedded nested list of individual line item objects, into a properly correctly structured set of nested Dart model classes?

Intermediate

Answer

Deserializing a genuinely nested JSON structure requires each individual outer model class's own fromJson constructor to properly delegate to the corresponding nested model class's own separate fromJson constructor for each individual embedded nested object or list, meaning a genuinely properly structured Order class's own fromJson method would itself call LineItem.fromJson for each individual item genuinely found within that order's own nested items array, correctly building up the entire genuinely properly nested object graph one distinct level at a time.
factory Order.fromJson(Map<String, dynamic> json) {
  return Order(
    id: json['id'],
    items: (json['items'] as List).map((item) => LineItem.fromJson(item)).toList(),
  );
}
Real-world example An order processing app properly deserializes a genuinely complex nested JSON order response containing an embedded list of individual line items, correctly building up a fully properly structured nested Order object containing a genuine list of separate typed LineItem objects.

Common follow-ups: How does this exact same specific nested deserialization pattern genuinely scale for a JSON structure containing several genuinely separate distinct levels of nesting?;Can json_serializable automatically genuinely handle this exact same kind of nested deserialization for you completely automatically?