Gson.toJson() 对比 JSONObject.toString()

Gson.toJson() vs JSONObject.toString()

#1 和#2 总是产生相同的输出吗? 使用一种解决方案比使用另一种解决方案有什么优势?

解决方案 #2 对我来说看起来更干净、更简单,它也更快吗?

解决方法一:

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)

方案二:

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
}

JSONObject is already included on Android API. If you want to use Gson,您必须将其作为 gradle 依赖项导入。

  compile 'com.google.code.gson:gson:<versionNumber>'

当然,导入的东西越多,.apk 就越大。

另一方面,GSon 为您提供了一系列注释,这使得 DX 更容易,因为您需要编写更少的代码。

我从来没有对它们进行过基准测试,所以我不会说任何关于性能的事情,但我相信它们都受益于 JsonObject,其下来自 Java.

两者Gson.toJson() and JSONObjet.toString()效果相同。他们将您的 JSON 对象和 return 作为字符串映射给您。