-3

我正在使用一个返回 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

4 回答 4

1

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

于 2012-11-18T09:09:43.260 回答
0

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

东西.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");
   }
 }  
于 2012-11-21T06:02:29.310 回答
0

http://www.codeproject.com/Articles/267023/Send-and-receive-json-between-android-and-php 我已经使用了这段代码。它非常简单直接。您必须稍微更改一下 json 格式。

于 2012-11-18T08:03:51.843 回答
0

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

Android 中的 GSON/杰克逊

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

然后您可以使用列表视图来显示分支对象的列表。例如,检查一下

于 2012-11-18T08:10:17.973 回答