如何从php服务器获取json数据到android手机
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11579693/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to get json data from php server to android mobile
提问by Jagdeep Singh
I am having an application in which I want to get json data from a php web server to android mobile. What I am having is a URL and hitting that URL gives me the json data like{"items":[{"latitude":"420","longitude":"421"}]}
. But I want to retrieve this json format in my android mobile and get the values of latitude and longitude from json format.
我有一个应用程序,我想在其中从 php web 服务器获取 json 数据到 android mobile。我拥有的是一个 URL,点击该 URL 会给我像 .json 这样的 json 数据{"items":[{"latitude":"420","longitude":"421"}]}
。但是我想在我的 android 手机中检索这个 json 格式,并从 json 格式中获取纬度和经度的值。
How can we get that on android mobile..?
我们怎么能在安卓手机上得到它..?
Thanks in advance..
提前致谢..
回答by Nirali
First do URL Connection
先做URL连接
String parsedString = "";
try {
URL url = new URL(yourURL);
URLConnection conn = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
InputStream is = httpConn.getInputStream();
parsedString = convertinputStreamToString(is);
} catch (Exception e) {
e.printStackTrace();
}
JSON String
JSON 字符串
{
"result": "success",
"countryCodeList":
[
{"countryCode":"00","countryName":"World Wide"},
{"countryCode":"kr","countryName":"Korea"}
]
}
Here below I am fetching country details
下面我正在获取国家/地区详细信息
JSONObject json = new JSONObject(jsonstring);
JSONArray nameArray = json.names();
JSONArray valArray = json.toJSONArray(nameArray);
JSONArray valArray1 = valArray.getJSONArray(1);
valArray1.toString().replace("[", "");
valArray1.toString().replace("]", "");
int len = valArray1.length();
for (int i = 0; i < valArray1.length(); i++) {
Country country = new Country();
JSONObject arr = valArray1.getJSONObject(i);
country.setCountryCode(arr.getString("countryCode"));
country.setCountryName(arr.getString("countryName"));
arrCountries.add(country);
}
public static String convertinputStreamToString(InputStream ists)
throws IOException {
if (ists != null) {
StringBuilder sb = new StringBuilder();
String line;
try {
BufferedReader r1 = new BufferedReader(new InputStreamReader(
ists, "UTF-8"));
while ((line = r1.readLine()) != null) {
sb.append(line).append("\n");
}
} finally {
ists.close();
}
return sb.toString();
} else {
return "";
}
}
回答by Ram kiran
String jsonStr = '{"menu": {' +
'"id": "file",' +
'"value": "File",' +
'"popup": {' +
'"menuitem": [' +
'{"value": "New", "onclick": "CreateNewDoc()"},' +
'{"value": "Open", "onclick": "OpenDoc()"},' +
'{"value": "Close", "onclick": "CloseDoc()"}' +
']' +
'}' +
'}}';
That JSON string is actually from http://json.org/example.html. It was the best one I could find for this given example.
该 JSON 字符串实际上来自http://json.org/example.html。对于这个给定的例子,这是我能找到的最好的。
Now that we have that in place, lets start using JSONObject
. You will need the following import for this to work: import org.json.JSONObject;
现在我们已经准备好了,让我们开始使用JSONObject
. 您将需要以下导入才能工作:import org.json.JSONObject;
JSONObject jsonObj = new JSONObject(jsonStr);
With that instantiated, we can do the following to retreive different pieces of data from the JSON string -
实例化后,我们可以执行以下操作以从 JSON 字符串中检索不同的数据片段 -
// grabbing the menu object
JSONObject menu = jsonObj.getJSONObject("menu");
Reading =========> HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
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();
result=sb.toString();=======>Here result is the json string
// these 2 are strings
String id = menu.getString("id");
String value = menu.getString("value");
// the popop is another JSON object
JSONObject popup = menu.getJSONObject("popup");
// using JSONArray to grab the menuitems from under popop
JSONArray menuitemArr = popupObject.getJSONArray("menuitem");
// lets loop through the JSONArray and get all the items
for (int i = 0; i < menuitemArr.length(); i++) {
// printing the values to the logcat
Log.v(menuitemArr.getJSONObject(i).getString("value").toString());
Log.v(menuitemArr.getJSONObject(i).getString("onclick").toString());
}
For a easy Example click here
一个简单的例子点击这里
回答by Vinay W
send a Request from your Android client
从您的 Android 客户端发送请求
public static JSONObject getJSONFromHttpPost(String URL) {
try{
// Create a new HttpClient and Post Header
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URL);
String resultString = null;
long t = System.currentTimeMillis();
HttpResponse response = (HttpResponse) httpclient.execute(httpPost);
System.out.println("HTTPResponse received in [" + (System.currentTimeMillis()-t) + "ms]");
// Get hold of the response entity (-> the data):
HttpEntity entity = response.getEntity();
if (entity != null) {
// Read the content stream
InputStream instream = entity.getContent();
// convert content stream to a String
resultString= convertStreamToString(instream);
instream.close();
System.out.println("result String : " + resultString);
//resultString = resultString.substring(1,resultString.length()-1); // remove wrapping "[" and "]"
System.out.println("result String : " + resultString);
// Transform the String into a JSONObject
JSONObject jsonObjRecv = new JSONObject(resultString);
// Raw DEBUG output of our received JSON object:
System.out.println("<JSONObject>\n"+jsonObjRecv.toString()+"\n</JSONObject>");
return jsonObjRecv;
}
}catch(Exception e){e.printStackTrace();}
return null;
}
}
here is the function to convert the string
这是转换字符串的函数
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line ="";
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
now all you have to do is echo
your string in JSON format on the server
现在您所要做的就是echo
在服务器上使用 JSON 格式的字符串
回答by Nermeen
Use something like:
使用类似的东西:
try {
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setSoTimeout(params, 0);
HttpClient httpClient = new DefaultHttpClient(params);
//prepare the HTTP GET call
HttpGet httpget = new HttpGet(urlString);
//get the response entity
HttpEntity entity = httpClient.execute(httpget).getEntity();
if (entity != null) {
//get the response content as a string
String response = EntityUtils.toString(entity);
//consume the entity
entity.consumeContent();
// When HttpClient instance is no longer needed, shut down the connection manager to ensure immediate deallocation of all system resources
httpClient.getConnectionManager().shutdown();
//return the JSON response
JSONObject object = new JSONObject(response.trim());
JSONArray jsonArray = object.getJSONArray("items");
if(jsonArray != null) {
for(int i = 0 ; i < jsonArray.length() ; i++) {
JSONObject object1 = (JSONObject) jsonArray.get(i);
String latitude = object1.getString("latitude");
String longitude = object1.getString("longitude");
}
}
}
}catch (Exception e) {
e.printStackTrace();
}