Problem parcing json
Не получается использовать данные, полученные через Retrofit + OkHTTP3 Получаю данные в приложение(в Loge вывожу, все данные присутствуют), не получается использовать эти данные, вроде создал модели, чтобы данные выводить на экран(возможно проблема в них),
Вот код:
Models:
data class Child(
@SerializedName("data")
@Expose
val childData: ChildData?
)
data class ChildData(
@SerializedName("title")
@Expose
val title: String?,
@SerializedName("num_comments")
@Expose
val numComments: Int?,
@SerializedName("created")
@Expose
val created: Int?,
@SerializedName("author")
@Expose
val author: String?,
@SerializedName("url")
@Expose
val url: String?
)
data class GlobalData(
@SerializedName("data")
@Expose
val globalData: News?
)
data class News(
@SerializedName("children")
@Expose
val data: List<Child>?
)
Network
interface ApiNews {
@GET("top.json")
suspend fun getNews(
): List<GlobalData>
}
data class Event<out T>(val status: Status, val data: T?, val error: Error?) {
companion object {
fun <T> loading(): Event<T> {
return Event(Status.LOADING, null, null)
}
fun <T> success(data: T?): Event<T> {
return Event(Status.SUCCESS, data, null)
}
fun <T> error(error: Error?): Event<T> {
return Event(Status.ERROR, null, error)
}
}
}
object NetworkService {
private const val BASE_URL = "https://www.reddit.com/"
private val loggingInterceptor = run {
val httpLoggingInterceptor = HttpLoggingInterceptor()
httpLoggingInterceptor.apply {
httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
}
}
private val baseInterceptor: Interceptor = invoke { chain ->
val newUrl = chain
.request()
.url
.newBuilder()
.build()
val request = chain
.request()
.newBuilder()
.url(newUrl)
.build()
return@invoke chain.proceed(request)
}
private val client: OkHttpClient = OkHttpClient
.Builder()
.addInterceptor(loggingInterceptor)
.addInterceptor(baseInterceptor)
.build()
fun retrofitService():ApiNews {
return Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build()
.create(ApiNews::class.java)
}
}
enum class Status {
SUCCESS,
ERROR,
LOADING
}
ViewModels:
class ActivityViewModel : NewsViewModel() {
val simpleLiveData = MutableLiveData<Event<List<GlobalData>>>()
fun getNews() {
requestWithLiveData(simpleLiveData) {
api.getNews()
}
}
}
abstract class NewsViewModel : ViewModel() {
var api: ApiNews = NetworkService.retrofitService()
fun <GlobalData> requestWithLiveData(
liveData: MutableLiveData<Event<List<GlobalData>>>,
request: suspend () -> List<GlobalData>
) {
liveData.postValue(Event.loading())
this.viewModelScope.launch(Dispatchers.IO) {
try {
val response = request.invoke()
if (!response.isNullOrEmpty()) {
liveData.postValue(Event.success(response))
} else {
liveData.postValue(Event.error(null))
}
} catch (e: Exception) {
e.printStackTrace()
liveData.postValue(Event.error(null))
}
}
}