0

I know this question has been answered at this post with same question. however, my question is the Json response by the most upvoted answer will be a json list with no key value. (you can also check the sample json from the official github website)

I am using Moshi library to parse json. However, I have no idea how to parse that Json list whose key value is not set.(only a list present in the Json with no Key value for that list) this is what it looks like though

[       
    {
    "id": 1296269,
    "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5",
    "...": "...",
    ...
    },   
    {
    "id": 1296255,
    "node_id": "somevalue",
    "...": "...",   
    }
    ...
]

since the purpose of asking this question is to get a list of repositories of a user, you could leave any code snippet to get that type of list Json to Kotlin data class.

I appreciate your help in advance.

foseja
  • 233
  • 2
  • 10
  • Not sure if your library can do the same thing, but this might help: https://stackoverflow.com/questions/60577860/how-to-retrieve-an-unnamed-json-array – Slaw Jun 29 '22 at 18:38

1 Answers1

0

Try this one for Array list

inline fun <reified T> Any?.getResponseInArrayList(): ArrayList<T?>? {
return try {
    val token: TypeToken<ArrayList<T>> = object : TypeToken<ArrayList<T>>() {}
    val json = Gson().toJson(this)
    Gson().fromJson(json, token.type)
} catch (e: Exception) {
    Log.e("GSON ERROR ", "" + e.message)
    null
}
}

use like this

val model =  yourJsonString.getResponseInArrayList<YouJsonModel>()
Amit pandey
  • 1,149
  • 1
  • 4
  • 15
  • what dependencies do I need to use TypeToken and Gson() here? – foseja Jun 29 '22 at 16:42
  • I added implementation 'com.google.code.gson:gson:2.9.0' dependency to use those TypeToken and Gson() but it didnt help. I assume your answer is not about how to get Json list into kotlin data class but about how to convert one type of object to another. I am having problem with getting the Json list into Kotlin data class. Thank you for your help though. – foseja Jun 29 '22 at 17:05