Reputation: 1337
Will #1 and #2 always produce the same output? What are the advantages of using one solution over the other one?
Solution #2 looks cleaner and simpler to me, is it faster also?
Solution one:
val gson = Gson()
val j = JsonObject() //com.google.gson
j.add("foo", gson.fromJson(getBar(), JsonElement::class.java))
val jString = gson.toJson(j)
Log.d(TAG,jString)
Solution two:
val j1 = JSONObject() //org.json
j1.put("foo", getBar())
val jString1 = j1.toString()
Log.d(TAG,jString1)
fun getBar() : String {
//do stuff and return a string
}
Upvotes: 2
Views: 3253
Reputation: 3713
JSONObject is already included on Android API. If you want to use Gson, you will have to import it as a gradle dependency.
compile 'com.google.code.gson:gson:<versionNumber>'
Of course, the more things you import, the bigger your .apk gets.
On the other hand, GSon feeds you with a series of annotations, which makes easier the DX since you have to write less code.
I never benchmarked them, so I won't say a thing about performance, but I do believe both of them benefits from JsonObject underneath which comes from Java.
Both Gson.toJson() and JSONObjet.toString() have the same effect. They map your JSON object and return to you as a String.
Upvotes: 2