2012-11-18 101 views
-4

我正在使用返回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; 
} 
} 

回答

1

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

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"); 
    } 
} 
相關問題