2013-07-10 80 views
1

如何檢索用於android的JSON Web服務數據?我目前正在嘗試以JSON格式檢索事件數據並顯示它,但我不確定該怎麼做。但不知何故,我無法在我的移動應用程序中運行。下面是我的代碼的示例:Json Web服務數據檢索

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; 

    } 
} 
+2

當您運行意外的代碼時會發生什麼?例外?電腦關機了?一位新教皇當選? :) –

+0

發佈你的堆棧跟蹤.. @JoachimIsaksson:lol –

+0

當我運行的代碼,沒有出來。只是黑屏! – Leo

回答

0

所以,如果字符串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(); 
} 

完蛋了。

+0

如果你覺得這個問題是重複的,而另一個問題已經有了答案,請將它標記爲這樣。複製和粘貼你的答案並不是那麼有效。 –

0

更換

// 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; 
     } 
    } 
+0

我的窗口小部件沒有顯示我從JSON解析中收到的數據:/ http://stackoverflow.com/questions/20082315/using-json-to-match-a-string-with-todays-date – Si8

0

檢查你JSONParser類:

你可能會做一個POST請求,該網址BU t將其不ALLOWED.You應該改變HTTP請求,鍵入GET

,如果你在你的代碼

HttpPost httpPost =新HttpPost(URL)找到; //然後改變它HTTPGET

ForExample:

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輸入..我希望你能理解這個問題。

UPDATE:

沒有哥們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"); 
+0

Yeap,我用來自博客的web服務代碼,並根據我的api將其更改爲我的。讓我張貼原始代碼! 至於id = json.getJSONArray(TAG_ID),我不確定哪個部分仍然出錯。從提供的鏈接「http://api.eventful.com/json/events/get?app_key=rDkKF6nSx6LjWTDR&id=E0-001-000324672-7」,有一個名爲「id」的json輸入:「E0-001- 000324672-7" 。這不是名稱爲ID的數組對象嗎?對不起,感謝您的幫助Shanku,感激不盡:) – Leo