Ktor中如何向FormData传递非字符串类型数据?
解决方案
方案1:将Attachment列表序列化为JSON字符串传递
如果后端支持接收JSON格式字符串作为attachments参数值,直接把列表转成JSON字符串就能满足需求,前提是你的项目引入了序列化库(比如kotlinx.serialization)。
操作步骤:
- 给
Attachment类添加序列化注解:
import kotlinx.serialization.Serializable @Serializable data class Attachment( val url: String, val title: String, val mimetype: String, val size: Int, val signedUrl: String )
- 修改请求代码,把列表序列化为JSON后传入:
import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json 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) // 将Attachment列表序列化为JSON字符串 append("attachments", Json.encodeToString(attachments)) } ) { apiKeyHeader() }.body()
方案2:用Multipart表单传递嵌套结构
如果后端要求严格遵循传统表单数组格式(比如attachments[0][url]这种参数名),可以改用submitMultipartForm构建请求:
suspend fun postGov( number: Int, closeLocation: String, closeTime: String, openLocation: String, openTime: String, attachments: List<Attachment> ): Gov = httpClient.submitMultipartForm( url = "$baseUrl/$GOVS_TABLE" ) { // 添加普通字段 append("number", number.toString()) append("close location", closeLocation) append("close time", closeTime) append("open location", openLocation) append("open time", openTime) // 遍历列表,逐个添加嵌套参数 attachments.forEachIndexed { index, attachment -> append("attachments[$index][url]", attachment.url) append("attachments[$index][title]", attachment.title) append("attachments[$index][mimetype]", attachment.mimetype) append("attachments[$index][size]", attachment.size.toString()) append("attachments[$index][signedUrl]", attachment.signedUrl) } } { apiKeyHeader() }.body()
补充说明
- 方案1代码更简洁,只要后端能解析JSON字符串就可以用,适合大多数场景;
- 方案2兼容性更强,符合传统表单提交的数组格式规范;
- 如果项目用Gson替代kotlinx.serialization,把
Json.encodeToString替换成Gson().toJson(attachments)即可。
内容的提问来源于stack exchange,提问作者Tus Die
相关产品推荐
相关产品推荐

