Kotlin字符串多符号替换:用actions元素替换占位符构建字符串
在Kotlin中实现基于JSON的多占位符字符串替换
需求说明
给定如下JSON结构,需要将title.text中的{0}、{1}等占位符,替换为actions数组中对应索引元素的text值,同时支持多actions的场景:
"title": { "text": "{0} shared a feeling", "actions": [ { "text": "User+021122", "action": "some_action" } ], "badgeName": "avatar-5" }
实现方案
通过数据类映射JSON结构 + MessageFormat处理占位符替换来实现,具体步骤如下:
1. 定义对应JSON的数据类
用Kotlin数据类映射JSON结构,方便后续解析和操作:
data class TitleConfig( val text: String, val actions: List<Action>, val badgeName: String? // 可选字段,根据实际JSON结构调整 ) data class Action( val text: String, val action: String )
2. 实现占位符替换函数
利用Java的MessageFormat类(Kotlin可直接调用)处理{0}格式的占位符,提取actions中的text作为替换参数:
import java.text.MessageFormat fun formatTitleText(titleConfig: TitleConfig): String { // 提取所有action的text作为替换参数数组 val replacementArgs = titleConfig.actions.map { it.text }.toTypedArray() // 执行占位符替换 return MessageFormat.format(titleConfig.text, *replacementArgs) }
3. 完整示例(含JSON解析)
结合Gson完成JSON解析与替换的完整流程(需添加Gson依赖):
import com.google.gson.Gson import java.text.MessageFormat data class TitleConfig( val text: String, val actions: List<Action>, val badgeName: String? ) data class Action( val text: String, val action: String ) fun formatTitleText(titleConfig: TitleConfig): String { val replacementArgs = titleConfig.actions.map { it.text }.toTypedArray() return MessageFormat.format(titleConfig.text, *replacementArgs) } fun main() { // 单action场景JSON val singleActionJson = """ { "text": "{0} shared a feeling", "actions": [ { "text": "User+021122", "action": "some_action" } ], "badgeName": "avatar-5" } """.trimIndent() // 多action场景JSON val multiActionJson = """ { "text": "{0} shared a feeling and {1} did nice job", "actions": [ { "text": "Alice", "action": "action1" }, { "text": "Bob", "action": "action2" } ], "badgeName": "avatar-3" } """.trimIndent() val gson = Gson() // 处理单场景 val singleConfig = gson.fromJson(singleActionJson, TitleConfig::class.java) println(formatTitleText(singleConfig)) // 输出: User+021122 shared a feeling // 处理多场景 val multiConfig = gson.fromJson(multiActionJson, TitleConfig::class.java) println(formatTitleText(multiConfig)) // 输出: Alice shared a feeling and Bob did nice job }
补充说明
- Gson依赖:如果使用Gson解析JSON,需在
build.gradle.kts(或build.gradle)中添加依赖:implementation("com.google.gson:gson:2.10.1") - 边界处理:如果需要校验占位符数量与
actions数量是否匹配,可以在替换函数中添加检查:fun formatTitleText(titleConfig: TitleConfig): String { val placeholderCount = Regex("\\{\\d+\\}").findAll(titleConfig.text).count() if (placeholderCount != titleConfig.actions.size) { throw IllegalArgumentException("Placeholder count doesn't match actions size") // 或返回原始文本:return titleConfig.text } val replacementArgs = titleConfig.actions.map { it.text }.toTypedArray() return MessageFormat.format(titleConfig.text, *replacementArgs) }
内容的提问来源于stack exchange,提问作者Jalson1982
相关产品推荐
相关产品推荐

