60

I need to convert a string {\"name\":\"test name\", \"age\":25} to a JSONObject

nkukday
  • 715
  • 1
  • 6
  • 7

4 Answers4

63

Perhaps I'm misunderstanding the question but it sounds like you are already using org.json which begs the question about why

val answer = JSONObject("""{"name":"test name", "age":25}""")

wouldn't be the best way to do it? What was wrong with the built in functionality of JSONObject?

Ryba
  • 1,249
  • 10
  • 17
  • 4
    Did you test your example using Kotlin? If yes, what version of the library did you use? If you try that with JSONObject version `org.json:json:20200518` you'll see that the contructor with a String object is not available in the JSONObject. – Alexandre V. Sep 29 '20 at 13:28
  • Yes actually and given that the answer was provided back in 2017 I'm sure there have been quite a number of changes that have taken place over the past 3 years. However, the link to which json version is in the original post's comment. Here is a direct link to the javadoc https://stleary.github.io/JSON-java/org/json/JSONObject.html – Ryba Oct 04 '20 at 15:16
  • I just pulled up the 20200518 version of the source code and see that it does still support the string constructor just fine. Line 405 on https://github.com/stleary/JSON-java/blob/8e5b516f2bab9b81098ef57a7e84076c28441428/JSONObject.java – Ryba Oct 04 '20 at 15:26
48
val rootObject= JSONObject()
rootObject.put("name","test name")
rootObject.put("age","25")
arjun shrestha
  • 1,379
  • 1
  • 10
  • 13
  • 7
    This answer assumes you already know the fields and values, which the asker can't know if they haven't parsed the string yet. – Ionoclast Brigham Mar 06 '19 at 18:14
  • 3
    How did this answer get so many upvotes!? It does not answer the question. The input data should be a JSON string, this example shows how to build a new JSONObject field by field. – Alexandre V. Sep 29 '20 at 13:23
  • 2
    I know this doesn't answer the OP's question, but this did help me understand how to easily create JSON out of my data objects without adding another lib to my project. – lasec0203 Dec 10 '20 at 04:02
18

You can use https://github.com/cbeust/klaxon library.

val parser: Parser = Parser()
val stringBuilder: StringBuilder = StringBuilder("{\"name\":\"Cedric Beust\", \"age\":23}")
val json: JsonObject = parser.parse(stringBuilder) as JsonObject
println("Name : ${json.string("name")}, Age : ${json.int("age")}")

Result :

Name : Cedric Beust, Age : 23
Akshar Patel
  • 8,998
  • 6
  • 35
  • 50
  • 2
    This way is more preferable if you going to use this object as a result of API method since `JsonObject` from **klaxon** knows how to serialize itself back to Json. – Andrew Kovalenko Aug 07 '17 at 19:41
  • 2
    `Parser()` is deprecated, use `Parser.default()` instead – Mugen Sep 18 '19 at 13:48
4

The approaches above are a bit dangerous: They don't provide a solution for illegal chars. They don't do the escaping... And we hate to do the escaping ourselves, don't we?

So here's what I did. Not that cute and clean but you have to do it only once.

class JsonBuilder() {
    private var json = JSONObject()

    constructor(vararg pairs: Pair<String, *>) : this() {
        add(*pairs)
    }

    fun add(vararg pairs: Pair<String, *>) {
        for ((key, value) in pairs) {
            when (value) {
                is Boolean -> json.put(key, value)
                is Number -> add(key, value)
                is String -> json.put(key, value)
                is JsonBuilder -> json.put(key, value.json)
                is Array<*> -> add(key, value)
                is JSONObject -> json.put(key, value)
                is JSONArray -> json.put(key, value)
                else -> json.put(key, null) // Or whatever, on illegal input
            }
        }
    }

    fun add(key: String, value: Number): JsonBuilder {
        when (value) {
            is Int -> json.put(key, value)
            is Long -> json.put(key, value)
            is Float -> json.put(key, value)
            is Double -> json.put(key, value)
            else -> {} // Do what you do on error
        }

        return this
    }

    fun <T> add(key: String, items: Array<T>): JsonBuilder {
        val jsonArray = JSONArray()
        items.forEach {
            when (it) {
                is String,is Long,is Int, is Boolean -> jsonArray.put(it)
                is JsonBuilder -> jsonArray.put(it.json)
                else -> try {jsonArray.put(it)} catch (ignored:Exception) {/*handle the error*/}
            }
        }

        json.put(key, jsonArray)

        return this
    }

    override fun toString() = json.toString()
}

Sorry, might have had to cut off types that were unique to my code so I might have broken some stuff - but the idea should be clear

You might be aware that in Kotlin, "to" is an infix method that converts two objects to a Pair. So you use it simply like this:

   JsonBuilder(
      "name" to "Amy Winehouse",
      "age" to 27
   ).toString()

But you can do cuter things:

JsonBuilder(
    "name" to "Elvis Presley",
    "furtherDetails" to JsonBuilder(
            "GreatestHits" to arrayOf("Surrender", "Jailhouse rock"),
            "Genre" to "Rock",
            "Died" to 1977)
).toString()
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Maneki Neko
  • 1,177
  • 1
  • 14
  • 24