I saw this issue many times, but still can't understand. It looks like I send request on site and it's body isn't correct. But why? May be I don't understand clearly how retrofit works, but do not I just collect a link for the request and wait for the answer from the server? Here is the link: here
An interface with request
public interface NService {
@GET("/computers?p=2")
Call<Model> getItems();
}
and class with base URL
public class APIUtils {
public static final String BASE_URL = "http://testwork.nsd.naumen.ru/rest/";
public static NService getMService() {
return RetrofitClient.getClient(BASE_URL).create(NService.class);
}
}
retrofit build class
public class RetrofitClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(String baseURL) {
if (retrofit==null) {
Gson gson = new GsonBuilder()
.setLenient()
.create();
retrofit = new Retrofit.Builder()
.baseUrl(baseURL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
return retrofit;
}
}
JSON were parsed though this
and MainActivity is:
public class MainActivity extends AppCompatActivity {
private List<Item> responseModel;
private NService mService;
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("testcrap", "before loading set");
setContentView(R.layout.activity_main);
mService = APIUtils.getMService(); // Строим retrofit объект, собираем ссылку
Log.d("testcrap", "before loading");
loadSomeCrap();
Log.d("testcrap", "after loading");
}
public void loadSomeCrap() {
Log.d("testcrap", "started parsing");
mService.getItems().enqueue(new Callback<Model>() {
@Override
public void onResponse(Call<Model> call, Response<Model> response) {
Log.d("testcrap", "started onResponse");
if(response.isSuccessful()) {
Log.d("testcrap", "posts loaded from API");
}else {
Log.d("testcrap", "posts not loaded from API");
}
}
@Override
public void onFailure(Call<Model> call, Throwable t) {
//showErrorMes sage();
Log.d("testcrap", t.toString());
}
});
}
}
Log:
before loading set
before loading
started parsing
after loading
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 13 column 1 path $
So, if it's wrong request, what should I change for normal work?
Your API or JSON response is returning JSON_OBJECT but you are getting it in String so this JsonSyntaxException is shown you. Try to fetch response in OBJECT.
Make these changes ..
BASE_URL = "http://testwork.nsd.naumen.ru/"
And then on interface ..
@GET("rest/computers?p=2")
.............
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.