【问题标题】:Json Web Service Data RetrievalJson Web 服务数据检索
【发布时间】:2013-07-10 06:53:48
【问题描述】:

如何检索 Android 的 JSON Web 服务数据?我目前正在尝试以 JSON 格式检索事件数据并显示它,但我不确定我应该怎么做。但不知何故,我无法在我的移动应用程序中运行。这是我的代码示例:

package com.androidhive.jsonparsing;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class AndroidJSONParsingActivity extends ListActivity {

    // url to make request
    private static String url = "http://api.eventful.com/json/events/get?app_key=rDkKF6nSx6LjWTDR&id=E0-001-000324672-7";

    // JSON Node names
    private static final String TAG_ID = "id";
    private static final String TAG_REGION = "region";
    private static final String TAG_STARTTIME = "start_time";
    private static final String TAG_TITLE = "title";
    private static final String TAG_CITY = "city";
    private static final String TAG_VENUE_NAME = "venue_name";

    // contacts JSONArray
    JSONArray id;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Hashmap for ListView
        ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();

        // Creating JSON Parser instance
        JSONParser jParser = new JSONParser();

        // getting JSON string from URL
        JSONObject json = jParser.getJSONFromUrl(url);

        try {
            // Getting Array of Contacts
            id = json.getJSONArray(TAG_ID);

            // looping through All Contacts
            for (int i = 0; i < id.length(); i++) {
                JSONObject c = id.getJSONObject(i);

                // Storing each json item in variable
                String mid = c.getString(TAG_ID);
                String region = c.getString(TAG_REGION);
                String starttime = c.getString(TAG_STARTTIME);
                String mtitle = c.getString(TAG_TITLE);
                String city = c.getString(TAG_CITY);
                String venuename = c.getString(TAG_VENUE_NAME);

                // creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();

                // adding each child node to HashMap key => value
                map.put(TAG_ID, mid);
                map.put(TAG_REGION, region);
                map.put(TAG_STARTTIME, starttime);
                map.put(TAG_TITLE, mtitle);
                map.put(TAG_CITY, city);
                map.put(TAG_VENUE_NAME, venuename);

                // adding HashList to ArrayList
                contactList.add(map);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(this, contactList,
                R.layout.list_item, new String[] { TAG_TITLE },
                new int[] { R.id.mtitle });

        setListAdapter(adapter);

        // selecting single ListView item
        ListView lv = getListView();

        // Launching new screen on Selecting Single ListItem
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting values from selected ListItem
                String name = ((TextView) view.findViewById(R.id.mtitle))
                        .getText().toString();

                // Starting new intent
                Intent in = new Intent(getApplicationContext(),
                        SingleMenuItemActivity.class);
                in.putExtra(TAG_TITLE, name);


            }
        });

    }

}

应要求,这是我的 JSONParser 示例代码:

package com.androidhive.jsonparsing;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();           

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

【问题讨论】:

  • 当您运行出乎意料的代码时会发生什么?例外?电脑关机? A new pope is elected? :)
  • 发布你的堆栈跟踪.. @JoachimIsaksson:大声笑
  • 当我运行代码时,什么也没有出现。只是黑屏!
  • 你在用模拟器吗??这是你第一次运行安卓项目吗???
  • 能不能发下JSONParser类代码

标签: java android json web-services events


【解决方案1】:

因此,如果 String strJson 是从 HTTP 请求接收到的结果字符串,例如必须填充到 ListView 中,那么:-

JSONObject strJsonObj = new JSONObject(strJson);
Listview listContent = getListFromJson(strJsonObj);

并从 strJsonObj 创建一个 JSON 数组,如:

JSONArray resultantArray = strJsonObj.getJSONArray("resultantTag");

循环遍历 JsonArray 为每次遍历创建 Json 对象:

for(int i=0; i<searchResultArray.length(); i++){
      JSONObject objAtI = (JSONObject) resultantArray.get(i);
      objAtI.get("xyz").toString();
      objAtI.get("abc").toString();
}

就是这样。

【讨论】:

  • 如果您觉得这个问题是重复的,并且另一个问题已经有答案,请标记为这样。复制和粘贴您的答案并没有那么有效。
【解决方案2】:

检查你的 JSONParser 类:

您可能正在向此网址发出 POST 请求,但不允许这样做。您应该将 HTTP 请求更改为键入 GET

如果你在你的代码中找到

HttpPost httpPost = new HttpPost(url); //然后改变它httpget

例如:

DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpGet method = new HttpGet(new URI("youurl"));
HttpResponse response = defaultHttpClient.execute(method);
InputStream data = response.getEntity().getContent();

我找到了你犯错的地方。可能您刚刚学会从博客创建 Web 服务,并根据您的要求对其进行了逐字更改。这里没有错,但您缺少的是 json 的输入格式。你提到的教程有不同的输入格式,你的 URL 有不同的格式。所以你需要相应地解析你的jsonobject..

id = json.getJSONArray(TAG_ID);没有名称为 id 的数组对象。请检查您的 json 输入。希望您理解问题所在。

更新:

no dude ID 不是链接中的对象数组(标签是)。所以你检索它的方式是错误的。我建议你学习json格式并解析它,它很简单。

举例

String data="{'foo':'bar','coolness':2.0, 'altitude':39000, 'pilot':{'firstName':'Buzz','lastName':'Aldrin'}, 'mission':'apollo 11'}";

我是这样检索的

JSONObject json = (JSONObject) JSONSerializer.toJSON(data);        
    double coolness = json.getDouble( "coolness" );
    int altitude = json.getInt( "altitude" );
    JSONObject pilot = json.getJSONObject("pilot");
    String firstName = pilot.getString("firstName");
    String lastName = pilot.getString("lastName");

    System.out.println( "Coolness: " + coolness );
    System.out.println( "Altitude: " + altitude );
    System.out.println( "Pilot: " + lastName );

因此,当您从方法接收 JSONObject 时,不要将其转换为 jsonarray。只需使用

String ID = json.getString("id");

【讨论】:

  • 是的,我使用博客中的 Web 服务代码并根据我拥有的 api 将其更改为我的。让我发布原始代码!至于 id = json.getJSONArray(TAG_ID),我不确定哪个部分仍然出错。在提供的链接中,“api.eventful.com/json/events/…”有一个名为“id”的 json 输入:“E0-001-000324672-7”。这不是名称为 id 的数组对象吗?很抱歉给您带来麻烦,感谢山库的帮助,非常感谢:)
【解决方案3】:

替换

// Creating JSON Parser instance
        JSONParser jParser = new JSONParser();

        // getting JSON string from URL
        JSONObject json = jParser.getJSONFromUrl(url);

String response = getRequest(url);
JSONObject object = new JSONObject(response);

添加这两个函数

public String getRequest(final String url) {
        String responseString=null;
        try {  

            Logger.show(Log.INFO, TAG,
                    "URL " +url);
            HttpParams httpParameters = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpParameters,
                    15000);
            HttpConnectionParams.setSoTimeout(httpParameters,15000);
            HttpClient client = new DefaultHttpClient(httpParameters);
            HttpGet request = new HttpGet();
            request.setURI(new URI(url));
            HttpResponse response = client.execute(request);
            InputStream ips  = response.getEntity().getContent();
            responseString = response.toString();
            responseString = intputStreamToStringConvertor(ips);

        } catch (NullPointerException e) {
            Logger.show(e);
            responseString = null;
        } catch (UnsupportedEncodingException e) {
            Logger.show(e);
            responseString = null;
        } catch (ClientProtocolException e) {
            Logger.show(e);
        } catch (IOException e) {
            Logger.show(e);
            responseString = null;
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        return responseString;
    }

    /** Converting InputStream to string */
    private static String intputStreamToStringConvertor(InputStream inputStream) {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    inputStream, "UTF-8"), 800);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            inputStream.close();
            return sb.toString();
        } catch (NullPointerException e) {
            Logger.show(e);
            return null;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-25
  • 2014-03-15
  • 1970-01-01
  • 2011-01-07
  • 1970-01-01
相关资源
最近更新 更多