Skip to content

[Bug in dartgen] list fields in toJson miss .toList(), causing jsonEncode failure #5629

Description

@fondoger

What happened

goctl api dartgen generates Dart toJson() methods for list fields using map(...) without converting the mapped iterable back to a List.

The generated object works for direct map inspection, but fails when passed to jsonEncode(obj.toJson()), because dart:convert cannot encode MappedListIterable.

Generated code

Example generated Dart code:

class GetTopUpProductsResponse {
  final List<TopUpProductItem?> items;

  Map<String, dynamic> toJson() {
    return {
      'items': items.map((i) => i?.toJson()),
    };
  }
}

Error log

Unhandled exception:
Converting object to an encodable object failed: Instance of 'MappedListIterable<TopUpProductItem, Map<String, dynamic>?>'

Expected generated code

The list field should be materialized with .toList():

Map<String, dynamic> toJson() {
  return {
    'items': items.map((i) => i?.toJson()).toList(),
  };
}

Minimal API shape that triggers it

GetTopUpProductsResponse {
    Items []*TopUpProductItem `json:"items"`
}
TopUpProductItem {
    ProductId string `json:"productId"`
}

Suspected source

The issue appears to come from tools/goctl/api/dartgen/gendata.go, where list field serialization is generated without appending .toList().

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions