Skip to content

[REQ] [Swift5] Encode a user-defined model to Json when using multipart/form-data #8925

Description

@0x0c

Is your feature request related to a problem? Please describe.

When sending any user-defined models as multipart/form-data, Xcode could not build generated codes because of missing a method called encodeToJSON that is a member of JSONEncodable protocol.
Although existing primitive types conforms to this protocol, user-defined model does not.

For example, Xcode could not build this API.

openapi: 3.0.0
info:
  title: test
  version: '1.0'
servers:
  - url: 'http://localhost:3000'
paths:
  /postModel:
    post:
      summary: Create New User
      operationId: post-user
      responses:
        '200':
          description: User Created
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
              examples: {}
        '400':
          description: Missing Required Information
      description: Create a new user.
      requestBody:
        content:
          multipart/form-data:
            schema:
              $ref: '#/components/schemas/Request'
    parameters: []
components:
  schemas:
    User:
      title: User
      type: object
      description: ''
      x-examples: {}
      properties:
        integerValue:
          type: integer
    Request:
      title: Request
      type: object
      properties:
        user1:
          $ref: '#/components/schemas/User'

Screen Shot 2021-03-09 at 1 14 33

Describe the solution you'd like

Implement encodeToJSON method for any user-defined models by protocol extension.

extension JSONEncodable where Self: Encodable {
    func encodeToJSON() -> Any {
        let encoder = JSONEncoder()
        guard let data = try? encoder.encode(self) else {
            fatalError("Could not encode to json: \(self)")
        }
        return data.base64EncodedString(options: Data.Base64EncodingOptions())
    }
}

Then, to confirm JSONEncodable for user-defined model, edit modelObject.mustache.

I already implement these codes and tested using 101da6e
If this request is acceptable, I will send PR.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions