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

问题描述:

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

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; 
} 
} 

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

您可以使用JACKSON库来解析响应数据。继后有一定的例子解析:

GSON/Jackson in Android

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

然后你可以使用List View显示分支对象的名单。例如,检查this out

+0

无法访问JSON元素,如分支ID和等通过JSON?我只使用JACKSON?谢谢 – user1797707

+0

请发布杰克逊解析代码和java bean类... –

您可以使用jObject.getString(name); 它返回名称映射的值

我用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"); 
    } 
}