我正在创建一个Android应用,用于控制使用RPI的调酒师的配置
我想在列表视图中显示所有当前的饮料及其成分。
这是我从服务器获得的Json响应:
[
{
"name":"Rum & Coke",
"ingredients":{
"rum":50,
"coke":150
}
},
{
"name":"Gin & Tonic",
"ingredients":{
"tonic":10,
"gin":10
}
},
{
"name":"Long Island",
"ingredients":{
"tequila":15,
"oj":30,
"rum":15,
"vodka":15,
"coke":100,
"gin":15
}
},
{
"name":"Screwdriver",
"ingredients":{
"vodka":50,
"oj":150
}
},
{
"name":"Margarita",
"ingredients":{
"mmix":150,
"tequila":50
}
},
{
"name":"Gin & Juice",
"ingredients":{
"oj":150,
"gin":50
}
},
{
"name":"Tequila Sunrise",
"ingredients":{
"tequila":50,
"oj":150
}
}
]
这是Drink.class
public class Drink {
@SerializedName("name")
private String name;
@SerializedName("ingredients")
private Map<String, Integer> ingredients;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Map<String, Integer> getIngredients() {
return ingredients;
}
public void setIngredients(Map<String, Integer> ingredients) {
this.ingredients = ingredients;
}
}
现在,我可以在列表视图中显示饮料名称,并且仅在地图的第二值上显示此for语句
Drink d = drinksArrayList.get(position);
System.out.println(d.getIngredients().size());
for (Map.Entry<String, Integer> ingredient : d.getIngredients().entrySet()) {
holder.ingredient0.setText(ingredient.getKey());
holder.ingredient1.setText(Integer.toString(ingredient.getValue()));
}
如果使用朗姆酒和焦炭,则此for语句将焦炭150打印到屏幕上。
有人知道如何正确序列化此Json并将其打印到列表视图吗?
答案 0 :(得分:2)
看起来json已正确反序列化,但是您使用了错误的字段来填充TextViews
。您应该使用getName
作为名称,即“朗姆酒和可乐”,然后将地图连接起来以获取成分列表。
我认为您想做这样的事情:
Drink d = drinksArrayList.get(position);
holder.ingredient0.setText(d.getName()));
StringBuilder ingredients = new StringBuilder();
for (Map.Entry<String, Integer> ingredient : d.getIngredients().entrySet()) {
ingredients.append(" ");
ingredients.append(ingredient.getKey());
ingredients.append(", ");
ingredients.append(Integer.toString(ingredient.getValue()));
ingredients.append("\n");
}
holder.ingredient1.setText(ingredients.toString().trim());