Skip to content

feat(response): #[ResponseBody] should serialize JsonI objects without metadata #142

Description

@usernane

Problem Statement

When a #[ResponseBody] method returns a JsonI object (e.g., from OpenAPIObj::toJSON()), the framework re-serializes it through its own serializer, which adds metadata fields (Value, Case, JsonXTagName, Style, Type) to each property. This produces unusable output for consumers expecting standard JSON (e.g., Swagger UI consuming an OpenAPI spec).

Current workaround:

return json_decode($spec->toJSON() . '', true);

This double-encodes and decodes just to get a plain array that the serializer won't pollute.

Proposed Solution

In the #[ResponseBody] handling logic (in WebService.php), detect when the return value is a JsonI instance and write its string representation directly to the response instead of re-serializing:

if ($result instanceof JsonI) {
    $response->addHeader('Content-Type', 'application/json');
    $response->write($result->toJSON());
} else if (is_array($result)) {
    // Current behavior
}

This way, returning $spec->toJSON() from a #[ResponseBody] method outputs clean JSON without metadata.

Alternatives Considered

  • Adding toArray() on OpenAPIObj — works but forces every consumer to discover the workaround individually.
  • Documenting the json_decode() workaround — doesn't fix the root cause.

Breaking Change

No

Additional Context

Discovered while building an OpenAPI spec endpoint using OpenAPIGenerator::generate(). The generated OpenAPIObj implements JsonI and its toJSON() produces valid OpenAPI 3.1 JSON, but #[ResponseBody] wraps it with serializer metadata making it incompatible with Swagger UI and other OpenAPI tools.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions