@Roman_Remeslo

Почему не работает Retrofit?

У меня есть сайт, который содержит в себе json. Я хочу распарсить, но ничего не выходит. Вот сайт: https://my-json-server.typicode.com/typicode/demo/posts

MainActivity.java:
package org.myapp.retrofittest;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.TextView;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {
    TextView text;
    Link link;
    String url = "https://my-json-server.typicode.com/typicode/";
    Retrofit retrofit;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        text = findViewById(R.id.text);
        retrofit = new Retrofit.Builder().baseUrl(url).addConverterFactory(GsonConverterFactory.create()).build();
        link = retrofit.create(Link.class);
        link.getSongs().enqueue(new Callback<GetData>() {
            @Override
            public void onResponse(Call<GetData> call, Response<GetData> response) {
                int id = response.body().getId();
                text.setText(String.valueOf(id));
            }

            @Override
            public void onFailure(Call<GetData> call, Throwable t) {
                text.setText("Fail");
            }
        });
    }
}

GetData.java:
package org.myapp.retrofittest;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class GetData {

    @SerializedName("id")
    @Expose
    private Integer id;
    @SerializedName("title")
    @Expose
    private String title;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

}

Link.java(Interface):
package org.myapp.retrofittest;

import retrofit2.Call;
import retrofit2.http.GET;

public interface Link {
    @GET("demo/posts/")
    Call<GetData> getSongs();
}
  • Вопрос задан
  • 275 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы