如何在android中解析JSON并在ListVIew中显示数据列表?

时间:2012-11-18 07:54:19

标签: android json

我正在使用一个返回JSON的Web服务作为响应。我想解析响应并列出一个对象列表。我不知道如何在Android中的UI中显示解析的数据。用户可以从列表中选择一个项目(即迪拜购物中心或迪拜媒体城或迪拜艺术节)。

public class MyLocation extends MapActivity {
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.location);

    initButtons();

    initMapView();
    initMyLocation();   
                    jObject=getJSONFile("http://loyaltier.com/app/mobile/code/places/Maps.php");
}
    private JSONObject getJSONFile(String URL) {
    JSONObject jObject=null;
    HttpGet httpGet=new HttpGet(URL); //http://loyaltier.com/app/mobile/code/places/Maps.php
    HttpClient httpClient=new DefaultHttpClient();
    HttpResponse httpResponse;
    StringBuilder stringBuilder=new StringBuilder();
    try{
        httpResponse=httpClient.execute(httpGet);
        HttpEntity httpEntity=httpResponse.getEntity();
        InputStream inputStream=httpEntity.getContent();
        int c;
        while((c=inputStream.read())!=-1){
            stringBuilder.append((char)c);
        }
    }catch(Exception e){
        e.printStackTrace();
    }
    try{
        jObject=new JSONObject(stringBuilder.toString());
    }catch(JSONException e){
        Log.e("Log_tags ", "Error parsing data "+e.toString());
    }
    return jObject;
} 
 }  

4 个答案:

答案 0 :(得分:1)

您可以使用jObject.getString(name); 它返回按名称

映射的值

答案 1 :(得分:0)

http://www.codeproject.com/Articles/267023/Send-and-receive-json-between-android-and-php 我使用过这段代码。它非常简单直接。 你必须稍微改变json格式。

答案 2 :(得分:0)

您可以使用JACKSON lib来解析响应数据。以下帖子有一些解析的例子:

GSON/Jackson in Android

http://w2davids.wordpress.com/android-json-parsing-made-easy-using-jackson/

然后您可以使用List View显示分支对象列表。例如,检查this out

答案 3 :(得分:0)

我用GSON编写,但程序没有在gsonFoo方法中显示log.i。为什么?有什么问题?

Thing.java:

package org.example.loyaltier;

public class Thing {
     String branchId=null;
     String branchCode=null;
     String branchName=null;
     String branchTel=null;
     String address=null;
     String cityName=null;
     String countryName=null;
     String latitude=null;
     String longitude=null;
     String workingHours=null;
}

MainActivity.java:

public class MyLocation extends MapActivity {
    public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.location);
         try {
             Log.i("THISSSSSSSSS", "ISSSSSSSSS");
             Log.i("FFOOOORRRR", "YYOUUUUUUUUU");
             gsonFoo();
          } catch (Exception e1) {
         Log.i("catch", "catch");
        // TODO Auto-generated catch block
        e1.printStackTrace();
   }
 }
 public void gsonFoo() throws Exception
 {
     Gson gson = new Gson();
     Thing thing = gson.fromJson(new                     FileReader("http://loyaltier.com/app/mobile/code/places/Maps.php"), Thing.class);
System.out.println(gson.toJson(thing));
    Log.i("GSOOOON", "FOOOO");
   }
 }