I am newbie, I have created webservice in java for get all Restaurant category from MySQL database and accessing in android studio ,
my json response is as following,
[
{
"restro": {
"categoryid": 1,
"categoryname": "Restaurant (Vegetarian)"
}
},
{
"restro": {
"categoryid": 2,
"categoryname": "Restaurant (Non-Vegetarian)"
}
}
]
deserialization code gson library
Gson gson=new Gson();
Type RestroTypeListType=new TypeToken<Collection<Category>>(){}.getType();
List<Category> categories=(List<Category>)gson.fromJson(jsonstring,RestroTypeListType);
tv1.setText("");
for(Category category : categories)
{
tv1.append(category.getCategoryName()+"\n");
}
my entity class is
public class Category {
private int categoryID;
private String categoryName;
public Category() {
}
public int getCategoryID() {
return categoryID;
}
public void setCategoryID(int categoryID) {
this.categoryID = categoryID;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
@Override
public String toString() {
return "Category{" +
", categoryName='" + categoryName + '\'' +
'}';
}
}
I am getting null in textview.
Your problem is that you are expecting a collection of categories but you are returning a collection of restro.
Can you provide more detail about the restro attribute in your json response.
But i guess that introducing a new Class that has an attribute named (restro) of type Category will solve your problem.
And change
Type RestroTypeListType=new TypeToken<Collection<Category>>(){}.getType();
For
Type RestroTypeListType=new TypeToken<Collection<Restro>>(){}.getType();
yeah, I got the answer
without add any external library ,
JSONArray jsonArray = new JSONArray(jsonstring);
String OuterstringArray;
tv1.setText("");
for (int outer = 0; outer < jsonArray.length(); outer++) {
OuterstringArray=jsonArray.getJSONObject(outer).getString("restro");
JSONObject jsonObject=new JSONObject(OuterstringArray);
arrayListRestro.add(jsonObject.getString("categoryname"));
}
ArrayAdapter arrayAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,arrayListRestro);
listRestros.setAdapter(arrayAdapter);
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.