0

It's my first time dealing with JSON in android studio, and I'm trying to parse the response from google books API to JSON and then retrieve some info about the volume such as the title, author, and the description. the problem is there are JSON objects within the main JSON. Should I create a data class for each JSON?

the API link 'https://www.googleapis.com/books/v1/volumes?q=kotlin'

how i'm parsing it

val jsonResponse = gson.fromJson(body, JsonResponse::class.java)

the data classes that i created

data class JsonResponse
 (val kind:String,val count:String,val items:List<JsonItems> )

data class JsonItems
  (val kind:String,
   val id:String,
   val etag:String,
   val self:String,
   val volumeInfo:List<VolumeInfo>,
   val saleInfo:List<SaleInfo>,
   val accessInfo:ListList<AccessInfo> ,
   val searchInfo:List<SearchInfo>)

is there any simpler solution to avoid unused data classes?

AskNilesh
  • 67,701
  • 16
  • 123
  • 163
yahyaBdd
  • 53
  • 1
  • 7

2 Answers2

0

You need to have these classes to be able to parse the json, but then you can just create objects of other classes using those data (and drop the earlier instances). Also, you don't need to include fields that you don't need.

Harry
  • 336
  • 1
  • 6
0

You can parse without data classes and you can use other tools than Gson.

I had a use case similar to yours. I did not want to write data classes, but just get direct access to the specific data I was interested in from a larger nested JSON object.

I found a solution that worked well for me here

https://johncodeos.com/how-to-parse-json-in-android-using-kotlin/ using JSONTokener https://developer.android.com/reference/org/json/JSONTokener

Based on these examples, some code for parsing books might look like:

// response is a String with the JSON body
val jsonObject = JSONTokener(response).nextValue() as JSONObject

val items = jsonObject.getString("items") as JSONArray
for (i in 0 until items.length()) {
    val volumeInfo = items.getJSONObject(i).getString("volumeInfo")
    val title = volumeInfo.getString("title")    

}

Another Stackoverflow post with other suggestions is here How to parse JSON in Kotlin?

user985366
  • 1,635
  • 3
  • 18
  • 39