Gson.toJson()与JSONObject.toString()

时间:2019-06-16 12:09:30

标签: android json kotlin gson 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
}

1 个答案:

答案 0 :(得分:0)

JSONObject已包含在Android API中。如果要使用Gson,则必须将其作为gradle依赖项导入。

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

当然,您导入的东西越多,.apk所得到的越大。

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

我从未对它们进行基准测试,因此我不会再谈性能,但我相信它们都受益于Java底层的JsonObject

Gson.toJson()JSONObjet.toString()的作用相同。它们映射您的JSON对象,并以字符串形式返回给您。

相关问题