如何使用moshi创建一个复杂的json而不定义类?

时间:2018-02-01 06:18:57

标签: android json kotlin moshi

在gson中,我可以使用JsonElement格式化复杂的json,类似于(在kotlin中):

    val objIDonotWantToDefine = JsonObject()

    objIDonotWantToDefine.addProperty("objName", "objIDonotWantToDefine")

    val playerJsonArray = JsonArray()
    for ((name, age) in players) {
        val player = JsonObject()
        player.addProperty("name", name)
        player.addProperty("age", age)
        playerJsonArray.add(player)
    }

    objIDonotWantToDefine.add("players", playerJsonArray)

    val jsonStringIWant = GsonBuilder().create().toJson(objIDonotWantToDefine)

我知道我可以在moshi中使用JsonWriter来做到这一点。但有一种简单的方法可以做到这一点吗?

1 个答案:

答案 0 :(得分:0)

感谢@Eric Cochran,我在这里发布解决方案演示:

说你想像这样创造json:

{
  "team": {
    "bestPlayers": [
      {
        "name": "kobe",
        "age": "20"
      },
      {
        "name": "shaq",
        "age": "30"
      }
    ],
    "name": "lakers",
    "playerCount": 2
  },
  "age": 999,
  "description": "hi, I'm a big nested json object"
}

然后你可以像这样编码:

val myNestedObj : MutableMap<String, Any> = LinkedHashMap()
myNestedObj.put("description", "hi, I'm a big nested json object")
myNestedObj.put("age", 999)
val layer1Obj  : MutableMap<String, Any> = LinkedHashMap()
layer1Obj.put("playerCount", 2)
layer1Obj.put("name", "lakers")

val playerJsonArray : MutableList<Map<String, String>> = ArrayList()
for ((name, age) in players) {
    val player : Map<String, String> = mapOf("name" to name, "age" to age)
    playerJsonArray.add(player)
}
layer1Obj.put("bestPlayers", playerJsonArray)

myNestedObj["team"] = layer1Obj

val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()

val jsonIWant = moshi.adapter(Map::class.java).toJson(myNestedObj)