JSON Web服务数据检索 [英] Json Web Service Data Retrieval
本文介绍了JSON Web服务数据检索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何检索JSON Web服务数据为Android?我目前正试图以JSON格式检索事件数据并显示它,但我真的不知道我该怎么做。但不知何故,我不能在我的手机应用程序运行。这里是我的code的样本:
包com.androidhive.jsonparsing;进口的java.util.ArrayList;
进口的java.util.HashMap;进口org.json.JSONArray;
进口org.json.JSONException;
进口org.json.JSONObject;进口android.app.ListActivity;
进口android.content.Intent;
进口android.os.Bundle;
进口android.util.Log;
进口android.view.View;
进口android.widget.AdapterView;
进口android.widget.AdapterView.OnItemClickListener;
进口android.widget.ListAdapter;
进口android.widget.ListView;
进口android.widget.SimpleAdapter;
进口android.widget.TextView;公共类AndroidJSONParsingActivity扩展ListActivity { // URL使请求
私有静态字符串URL =http://api.eventful.com/json/events/get?app_key=rDkKF6nSx6LjWTDR&id=E0-001-000324672-7; // JSON节点名称
私有静态最后弦乐TAG_ID =ID;
私有静态最后弦乐TAG_REGION =区域;
私有静态最后弦乐TAG_STARTTIME =START_TIME;
私有静态最后弦乐TAG_TITLE =称号;
私有静态最后弦乐TAG_CITY =城市;
私有静态最后弦乐TAG_VENUE_NAME =venue_name; //接触JSONArray
JSONArray ID; @覆盖
公共无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.main); //为哈希映射的ListView
ArrayList的<&HashMap的LT;字符串,字符串>> contactList =新的ArrayList<&HashMap的LT;字符串,字符串>>(); //创建JSON解析器实例
JSONParser jParser =新JSONParser(); // URL从获取JSON字符串
JSONObject的JSON = jParser.getJSONFromUrl(URL); 尝试{
//获取联系人的数组
ID = json.getJSONArray(TAG_ID); //通过所有联系人循环
的for(int i = 0; I< id.length();我++){
JSONObject的C = id.getJSONObject(I) //存储在变量中的每个JSON项目
字符串中旬= c.getString(TAG_ID);
字符串区域= c.getString(TAG_REGION);
字符串开始时间= c.getString(TAG_STARTTIME);
字符串mtitle = c.getString(TAG_TITLE);
字符串城市= c.getString(TAG_CITY);
字符串venuename = c.getString(TAG_VENUE_NAME); //创建新的HashMap
HashMap的<字符串,字符串>地图=新的HashMap<字符串,字符串>(); //将每个子节点的HashMap键=>值
map.put(TAG_ID,中旬);
map.put(TAG_REGION,区);
map.put(TAG_STARTTIME,开始时间);
map.put(TAG_TITLE,mtitle);
map.put(TAG_CITY,市);
map.put(TAG_VENUE_NAME,venuename); //添加HashList到ArrayList的
contactList.add(地图);
}
}赶上(JSONException E){
e.printStackTrace();
} / **
*更新解析JSON数据到ListView控件
* * /
ListAdapter适配器=新SimpleAdapter(这一点,contactList,
R.layout.list_item,新的String [] {} TAG_TITLE,
新的INT [] {R.id.mtitle}); setListAdapter(适配器); //选择单个ListView项
ListView控件LV = getListView(); //在选择单列表项启动新画面
lv.setOnItemClickListener(新OnItemClickListener(){ @覆盖
公共无效onItemClick(适配器视图<>母公司,观景,
INT位置,长的id){
//从选定的ListItem得到的值
字符串名称=((的TextView)view.findViewById(R.id.mtitle))
.getText()的toString()。 //开始新意图
在意向=新意图(getApplicationContext()
SingleMenuItemActivity.class);
in.putExtra(TAG_TITLE,名);
}
}); }}
的要求,这是我的示例code为JSONParser:
包com.androidhive.jsonparsing;进口java.io.BufferedReader中;
进口java.io.IOException异常;
进口的java.io.InputStream;
进口java.io.InputStreamReader中;
进口java.io.UnsupportedEncodingException;进口org.apache.http.HttpEntity;
进口org.apache.http.Htt presponse;
进口org.apache.http.client.ClientProtocolException;
进口org.apache.http.client.methods.HttpPost;
进口org.apache.http.impl.client.DefaultHttpClient;
进口org.json.JSONException;
进口org.json.JSONObject;进口android.util.Log;公共类JSONParser { 静态InputStream为= NULL;
静态的JSONObject jObj = NULL;
静态JSON字符串=; //构造
公共JSONParser(){ } 公众的JSONObject getJSONFromUrl(字符串URL){ //使HTTP请求
尝试{
// defaultHttpClient
DefaultHttpClient的HttpClient =新DefaultHttpClient();
HttpPost httpPost =新HttpPost(URL); HTT presponse HTT presponse = httpClient.execute(httpPost);
HttpEntity httpEntity = HTT presponse.getEntity();
是= httpEntity.getContent(); }赶上(UnsupportedEncodingException五){
e.printStackTrace();
}赶上(ClientProtocolException E){
e.printStackTrace();
}赶上(IOException异常五){
e.printStackTrace();
} 尝试{
读者的BufferedReader =新的BufferedReader(新的InputStreamReader(
是,ISO-8859-1),8);
StringBuilder的SB =新的StringBuilder();
串线= NULL;
而((行= reader.readLine())!= NULL){
sb.append(行+\\ n);
}
is.close();
JSON = sb.toString();
}赶上(例外五){
Log.e(缓冲区错误,错误转换结果+ e.toString());
} //尝试分析字符串到一个JSON对象
尝试{
jObj =新的JSONObject(JSON);
}赶上(JSONException E){
Log.e(JSON解析器,错误分析数据+ e.toString());
} //返回JSON字符串
返回jObj; }
}
解决方案
替换
//创建JSON解析器实例
JSONParser jParser =新JSONParser(); // URL从获取JSON字符串
JSONObject的JSON = jParser.getJSONFromUrl(URL);
与
字符串响应=调用getRequest(URL);
的JSONObject对象=新的JSONObject(响应);
添加这两种功能
公共字符串调用getRequest(最终字符串URL){
字符串responseString = NULL;
尝试{ Logger.show(Log.INFO,TAG,
URL+网址);
的HttpParams httpParameters =新BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters,
15000);
HttpConnectionParams.setSoTimeout(httpParameters,15000);
HttpClient的客户端=新DefaultHttpClient(httpParameters);
HTTPGET请求=新HTTPGET();
request.setURI(新的URI(URL));
HTT presponse响应= client.execute(请求);
InputStream的IPS = response.getEntity()的getContent()。
responseString = response.toString();
responseString = intputStreamToStringConvertor(IPS); }赶上(NullPointerException异常五){
Logger.show(E);
responseString = NULL;
}赶上(UnsupportedEncodingException五){
Logger.show(E);
responseString = NULL;
}赶上(ClientProtocolException E){
Logger.show(E);
}赶上(IOException异常五){
Logger.show(E);
responseString = NULL;
}赶上(的URISyntaxException E){
e.printStackTrace();
}
返回responseString;
} / **的InputStream转换为字符串* /
私人静态字符串intputStreamToStringConvertor(的InputStream的InputStream){
尝试{
读者的BufferedReader =新的BufferedReader(新的InputStreamReader(
InputStream的,UTF-8),800);
StringBuilder的SB =新的StringBuilder();
串线= NULL;
而((行= reader.readLine())!= NULL){
sb.append(行+\\ n);
}
inputStream.close();
返回sb.toString();
}赶上(NullPointerException异常五){
Logger.show(E);
返回null;
}赶上(UnsupportedEncodingException五){
e.printStackTrace();
返回null;
}赶上(IOException异常五){
e.printStackTrace();
返回null;
}
}
How to retrieve JSON web service data for android? I'm currently trying to retrieve event data in JSON format and display it but I'm not really sure how should I do it. But somehow I just can't run in my mobile application. Here is a sample of my code:
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);
}
});
}
}
As Requested, this is my sample code for 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;
}
}
解决方案
Replace
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
with
String response = getRequest(url);
JSONObject object = new JSONObject(response);
Add these two functions
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;
}
}
这篇关于JSON Web服务数据检索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文