【发布时间】:2019-06-14 12:18:51
【问题描述】:
我在我的应用程序中使用 Retrofit 将数据从 JSON 读取到我的应用程序。我有这个 JSON。 (我尝试了很多解决方案,但对我没有任何效果)。请帮助我。我在其他 JSON 中使用了相同的代码代码,它适用于 This JSON URL,但不适用于我的 JSON
JSON My JSON is placed at this URL
我的界面:
public interface SanaApi {
String BASE_URL = "http://www.hhfoodies.com/salesnotifier/";
@GET("sana_safinaz.php")
Call<List<SanaSafinas>> getSana();
}
这是模型类:
public class SanaSafinas {
private String id;
private String off;
private String image;
private String title;
private String sale_price;
private String original_price;
public SanaSafinas(String id, String off, String image, String title, String sale_price, String original_price) {
this.id = id;
this.off = off;
this.image = image;
this.title = title;
this.sale_price = sale_price;
this.original_price = original_price;
}
public String getId() {
return id;
}
public String getOff() {
return off;
}
public String getImage() {
return image;
}
public String getTitle() {
return title;
}
public String getSale_price() {
return sale_price;
}
public String getOriginal_price() {
return original_price;
}
}
这是主要活动:
public class MainActivity extends AppCompatActivity {
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listViewHeroes);
//calling the method to display the heroes
getSana();
}
private void getSana() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(SanaApi.BASE_URL)
.addConverterFactory(GsonConverterFactory.create()) //Here we are using the GsonConverterFactory to directly convert json data to object
.build();
SanaApi api = retrofit.create(SanaApi.class);
Call<List<SanaSafinas>> call = api.getSana();
call.enqueue(new Callback<List<SanaSafinas>>() {
@Override
public void onResponse(Call<List<SanaSafinas>> call, Response<List<SanaSafinas>> response) {
List<SanaSafinas> heroList = response.body();
//Creating an String array for the ListView
String[] heroes = new String[heroList.size()];
//looping through all the heroes and inserting the names inside the string array
for (int i = 0; i < heroList.size(); i++) {
heroes[i] = heroList.get(i).getSale_price();
}
//displaying the string array into listview
listView.setAdapter(new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, heroes));
}
@Override
public void onFailure(Call<List<SanaSafinas>> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
【问题讨论】:
-
您的模型类没有正确创建,好像您看到响应所有数据都在数据 JsonArray 中,并且您直接在那里工作,请更改您的模型类以使其正常工作
-
复制你在jsonschema2pojo.org中的所有响应,它会自动创建你的模型类目标语言:java源类型:JSON注释样式:Gson并检查包括getter和setter
标签: android json retrofit retrofit2