json响应为Map

时间:2019-01-04 12:17:14

标签: json parsing kotlin

我无法将JSON响应作为Map对象获取。

import com.google.gson.*
import org.jsoup.*
import com.google.gson.JsonPrimitive
import com.google.gson.JsonElement
// 1 count=10 at response
fun getFilms(count: Int = 1): Unit {
    var n: Int = 0
    val builder: GsonBuilder = GsonBuilder()
    val gson = builder.create()
    while(n <= count) {
        val doc: Document = Jsoup.connect("https://www.lostfilm.tv/ajaxik.php?act=serial&type=search&o=${n*10}&s=3&t=0").get()
        val data = doc.body().text().trimIndent()
        val prData: JsonObject = JsonParser().parse(data).getAsJsonObject()
        n++
        println(prData["data"].toString().replace("[", "").replace("]", ""))
    }
}

使用这种依赖

   <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.5</version>
        </dependency>
        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.8.3</version>
        </dependency>

我想将JSON响应提取为Map,但我不能这样做,我不知道要这样做,可以使用值的键提取数据。

2 个答案:

答案 0 :(得分:0)

import com.google.gson.*
import org.jsoup.*
import com.google.gson.JsonElement
import com.google.gson.JsonObject


fun getFilms(count: Int = 1): HashMap<Int, JsonObject> {
    var n: Int = 0
    val builder: GsonBuilder = GsonBuilder()
    val gson = builder.create()
    val ans = hashMapOf<Int, JsonObject>()
    while (n <= count) {
        val doc = Jsoup.connect("https://www.lostfilm.tv/ajaxik.php?act=serial&type=search&o=${n * 10}&s=3&t=0").get()
        val data = doc.body().text().trimIndent()
        val prData = JsonParser().parse(data).getAsJsonObject()
        ans.put(n, prData)
        n++
//        println(prData["data"].toString().replace("[", "").replace("]", ""))
    }
    return ans
}

fun main(args: Array<String>) {

    val films = getFilms(2)
    films.forEach { (key, value) ->
        var data = value.get("data").asJsonArray
        data.forEach {
            val obj = it.asJsonObject //since you know it's a JsonObject
            val entries = obj.entrySet()
            entries.forEach {
                println("${it.key},${it.value}") //her is your key value 

            }
        }
    }
}

输出示例:

rating,7.7
title,"Страна приливов"
title_orig,"Tidelands"
date,"2018"
link,"/series/Tidelands"
alias,"Tidelands"
not_favorited,true
id,"399"
has_icon,"1"
has_image,true
img,"//static.lostfilm.tv/Images/399/Posters/image.jpg"
genres,"Криминал, Драма, Мистика"
channels,"Netflix"
status,7
status_7,true
status_auto,2
status_auto_2,true
status_season,"1"
rating,8.2
title,"Летящие сквозь ночь"
title_orig,"Nightflyers"
date,"2018"
link,"/series/Nightflyers"
alias,"Nightflyers"
not_favorited,true
id,"398"
has_icon,"1"
has_image,true
img,"//static.lostfilm.tv/Images/398/Posters/image.jpg"
genres,"Ужасы, Драма, Фантастика"
channels,"Syfy"
status,7
status_7,true
status_auto,1
status_auto_1,true
status_season,"1"
rating,8.9
title,"Побег из Даннеморы"
title_orig,"Escape at Dannemora"
date,"2018"
link,"/series/Escape_at_Dannemora"

答案 1 :(得分:0)

简单的选项-如果可能的话-将创建一个DTO类,并让Gson完成这项工作。在您的URL DTO中查看响应可能像:

data class Response(
    val data: Array<Map<String, String>>, // There is an array named 'data'
                                          // having name/value pair maps.
    val letters: Map<Int, Boolean>,       // This can also be a map.
    val result: String
)

然后使用JsonParser实例代替使用Gson。请参见以下功能的示例:

@Test
fun test() {
    // Setted n = 1 in the url fir this test
    val url =
        "https://www.lostfilm.tv/ajaxik.php?act=serial&type=search&o=${1*10}&s=3&t=0"
    val doc: Document = Jsoup.connect(url).get()
    // Pretty print just in case you want ot print out also
    val gson = GsonBuilder().setPrettyPrinting().create();
    val res = gson.fromJson(doc.body().text(), Response::class.java)
    // Print out the first data item's value with key "title"
    log.info(res.data[0].get("title"))
}

这应该打印出类似的内容(假设数据不变):

  

Наследие

似乎实际数据是固定的,因此您也可以为此创建DTO,但这取决于情况是否可取/需要或更方便。