我正在获取JSON数据。下载时如何使用JSONArray&在GridView中显示图像。我怎么能做到这一点?我指的是Download and Display Image in Android GridView。它是JSONObject。
这是我的代码。
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONArray posts = response.optJSONArray("posts");
GridItem item;
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.optJSONObject(i);
item = new GridItem();
JSONArray img = post.getJSONArray("img");
if (null != attachments && attachments.length() > 0) {
JSONObject attachment = attachments.getJSONObject(0);
if (img!= null)
item.setImage(img.getString("url"));
}
mGridData.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
这里是推荐代码,
{
"status": "ok",
"count": 45,
"count_total": 397,
"pages": 9,
"posts": [
{
"id": 12378,
"url": "http://stacktips.com/tutorials/android/speech-to-text-in-android",
},
{...},
{...}
]
}
这是我的JSON,
[
{
"id": "95",
"name": "Cherry",
"menu": [
{
"menu_id": "18",
"img": "925dd3ad6d50fa5686a82af26515be5d.jpg"
}
]
},
{...},
{...}
]
答案 0 :(得分:1)
试试这段代码:
参考代码:
try{
JSONObject object = new JSONObject (result);
JSONArray jsonArray = object.getJSONArray("posts");
for(int i=0;i<jsonArray.length();i++){
JSONObject object = jsonArray.getJSONObject(i);
String id = object.getString("id");
String img_url = object.getString("url");
item = new GridItem();
if (img_url!= null)
item.setImage(img_url);
mGridData.add(item);
}
}
catch (JSONException e){
e.printStackTrace();
}
第二个JSON
try{
JSONArray jsonArray = new JSONArray(result);
for(int i=0;i<jsonArray.length();i++){
JSONObject object = jsonArray.getJSONObject(i);
String id = object.getString("id");
String name = object.getString("name");
JSONArray menu = object.getJSONArray("menu");
for(int j=0;j<menu.length();j++){
JSONObject menu_object = menu.getJSONObject(j);
String menu_id = menu_object.getString("menu_id");
String image_url = menu_object.getString("img");
item = new GridItem();
if (image_url!= null)
item.setImage(image_url);
mGridData.add(item);
}
}
}
catch (JSONException e){
e.printStackTrace();
}
答案 1 :(得分:1)
以下是您的解决方案:
try {
JSONObject response = new JSONObject(result);
JSONArray menu = response.optJSONArray("menu");
GridItem item;
for (int i = 0; i < menu.length(); i++) {
JSONObject post = menu.optJSONObject(i);
String menu_id=post.getString("menu_id");
String img=post.getString("img");
item = new GridItem();
item.setImage(img);
mGridData.add(item);
}
}
}
答案 2 :(得分:0)
请使用google-gson图书馆link
示例JSON字符串
class Albums {
public String title;
public String message;
public List<string> errors = new ArrayList<string>();
public String total;
public int total_pages;
public int page;
public String limit;
List<dataset> dataset = new ArrayList<dataset>();
}
<强> Albums.java 强>
Albums albums = gson.fromJson(jsonString, Albums.class);
主要类
cardView