You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin中如何移除JSON特定字段值的引号?

Fixing JSON Array Serialization in Kotlin

Hey there! Let's sort out that JSON formatting issue you're facing. The problem with your current code is that you're converting the JsonArray to a string and manually mucking with quotes, which forces the JSON serializer to treat your array as a plain string value (hence the extra quotes around [415918]). Instead, we should let the JSON library handle the array natively—no string replacements needed.

The Correct Approach

Instead of converting your JsonArray to a string, pass the actual JsonArray object directly to JSONObject.put(). Here's the cleaned-up code:

// Step 1: Build your array normally
val array = JsonArray()
array.add(id.toString()) // Use array.add(id) if id is a numeric type instead

// Step 2: Create the inner JSON object with the array as a native value
val innerJson = JSONObject().apply {
    put("a", "value_a")
    put("b", "value_b")
    put("c", array) // No toString() or replace() here!
}

// Step 3: Wrap it in the outer testJson object
val testObj = JSONObject().apply {
    put("testJson", innerJson) // Again, pass the JSONObject directly
}

// Step 4: Get the final valid JSON string
val finalJsonString = testObj.toString()

What This Produces

The resulting JSON will look exactly like you want:

{"testJson":{"a":"value_a","b":"value_b","c":["415918"]}}

Now the c field is a proper JSON array, not a quoted string.

Bonus: Use Modern Kotlin JSON Libraries (Even Easier!)

If you're open to using more idiomatic Kotlin tools, libraries like kotlinx.serialization or Gson make this even cleaner and type-safe. Here's an example with kotlinx.serialization:

First, add the library dependencies (follow your project's setup guidelines), then define data classes:

import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json

@Serializable
data class InnerPayload(
    val a: String = "value_a",
    val b: String = "value_b",
    val c: List<String>
)

@Serializable
data class TestPayload(val testJson: InnerPayload)

Then serialize your data in one line:

val payload = TestPayload(InnerPayload(c = listOf(id.toString())))
val finalJsonString = Json.encodeToString(payload)

This eliminates manual JSON construction entirely and reduces the chance of formatting errors.

内容的提问来源于stack exchange,提问作者Andrew

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 10:03:14