大家好,我最近依然在Android上使用Retrofit API抓取Json時,遇到底下這個問題:
這個是API的規格:
Postman有回傳一個數字給我,但我在Android上不知道要怎麼取得這個數字
這邊是我的程式碼:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://10.25.7.167:62678/")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiGet apiGet =retrofit.create(ApiGet.class);
Call<test> call = apiGet.getPost();
call.enqueue(new Callback<test>() {
@Override
public void onResponse(Call<test> call, Response<test> response) {
Log.d("API","是:"+response.body().getInteger());
}
@Override
public void onFailure(Call<test> call, Throwable t) {
Log.d("API","Fail:"+t.toString());
}
});
}
public interface ApiGet{
@GET("api/Commodity/GetIdCommodityByIdCommodityDetail?idCommodityDetail=3474")
Call<test> getPost();
}
public class test{
private int integer;
public int getInteger() {
return integer;
}
public void setInteger(int integer) {
this.integer = integer;
}
}
}
會出這個錯誤
D/API: Fail:com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was NUMBER at line 1 column 5 path $
我看不懂
你自己試試看
Retrofit.Builder()
.baseUrl("<base url>")
.client(client)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create(gson))
.build()