kotlin 如何传递给FormData不是一个字符串?克托尔

avwztpqn  于 2023-10-23  发布在  Kotlin
关注(0)|答案(1)|浏览(139)
suspend fun postGov(
        number: Int,
        closeLocation: String,
        closeTime: String,
        openLocation: String,
        openTime: String,
        attachments: List<Attachment>
    ): Gov = httpClient.submitForm(
        url = "$baseUrl/$GOVS_TABLE",
        formParameters = parameters {
            append("number", number.toString())
            append("close location", closeLocation)
            append("close time", closeTime)
            append("open location", openLocation)
            append("open time", openTime)
            append("attachments", attachments)
        }
    ) {
        apiKeyHeader()
    }.body()

append只接受字符串,我需要向FormData传递一个项目列表,这样FormData就像这样

{
  "number": "123",
  "close time": "string",
  "close location": "string",
  "open time": "string",
  "open location": "string",
  "attachments": [{"url":"https://nocohub-001-prod-app-attachments.s3.us-east-2.amazonaws.com/nc/uploads/2023/10/21/08bca39258b20ad3e4300f2a76169d3fb02c5249/HPM8jgzGzuJqLDDbbk.png","title":"ktor_logo.png","mimetype":"image/jpeg","size":30207,"signedUrl":"https://nocohub-001-prod-app-attachments.s3.us-east-2.amazonaws.com/nc/uploads/2023/10/21/08bca39258b20ad3e4300f2a76169d3fb02c5249/HPM8jgzGzuJqLDDbbk.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&X-Amz-Credential=AKIATUJCOBWTKOMQ5JMU%2F20231021%2Fus-east-2%2Fs3%2Faws4_request&X-Amz-Date=20231021T104627Z&X-Amz-Expires=7413&X-Amz-Signature=f11c2918fd2e2c49caab3d405f794650dbad75dd5abcb52476bda3afdc56c96f&X-Amz-SignedHeaders=host&x-id=GetObject"}]
}

我试着深入挖掘源代码,但没有找到一个方便的选择

huwehgph

huwehgph1#

来自KotlinXSerialization的EncodeToString帮助了我们。
这个方法使json从list中提取字符串。

import kotlinx.serialization.encodeToString

suspend fun postGov(
        number: Int,
        closeLocation: String,
        closeTime: String,
        openLocation: String,
        openTime: String,
        attachments: List<Attachment>
    ): Gov = httpClient.submitForm(
        url = "$baseUrl/$GOVS_TABLE",
        formParameters = parameters {
            append("number", number.toString())
            append("close location", closeLocation)
            append("close time", closeTime)
            append("open location", openLocation)
            append("open time", openTime)
            append("attachments", Json.encodeToString<List<Attachment>>(attachments))
        }
    )

相关问题