Kotlin中如何移除JSON特定字段值的引号?
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

