Skip to content

Instantly share code, notes, and snippets.

@nglauber
Last active July 5, 2020 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nglauber/8a3c39db47813483d788fb2914f0f21f to your computer and use it in GitHub Desktop.
Save nglauber/8a3c39db47813483d788fb2914f0f21f to your computer and use it in GitHub Desktop.
package com.example.bookscompose.http
import com.google.gson.annotations.SerializedName
data class Book(
@SerializedName("titulo")
var title: String = "",
var category: String = "",
@SerializedName("autor")
var author: String = "",
@SerializedName("ano")
var year: Int = 0,
@SerializedName("paginas")
var pages: Int = 0,
@SerializedName("capa")
var coverUrl: String = ""
)
package com.example.bookscompose.http
import com.google.gson.Gson
import okhttp3.OkHttpClient
import okhttp3.Request
import java.util.concurrent.TimeUnit
object BookHttp {
private const val BOOK_JSON_URL = "https://raw.githubusercontent.com/nglauber/dominando_android2/master/livros_novatec.json"
fun loadBooksGson(): List<Book>? {
val client = OkHttpClient.Builder()
.readTimeout(5, TimeUnit.SECONDS)
.connectTimeout(10, TimeUnit.SECONDS)
.build()
val request = Request.Builder()
.url(BOOK_JSON_URL)
.build()
try {
val response = client.newCall(request).execute()
val json = response.body?.string()
val gson = Gson()
val publisher = gson.fromJson<Publisher>(json, Publisher::class.java)
return publisher.categories
.flatMap { category ->
category.books.forEach { book ->
book.category = category.name
}
category.books
}
} catch (e: Exception) {
e.printStackTrace()
}
return null
}
}
package com.example.bookscompose.http
import com.google.gson.annotations.SerializedName
data class Category(
@SerializedName("categoria")
var name: String = "",
@SerializedName("livros")
var books: List<Book> = emptyList()
)
package com.example.bookscompose.http
import com.google.gson.annotations.SerializedName
data class Publisher (
@SerializedName("novatec")
var categories: List<Category> = emptyList()
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment