如何获得JSON数据从PHP服务器到Android手机 [英] how to get json data from php server to android mobile

查看:90
本文介绍了如何获得JSON数据从PHP服务器到Android手机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有在其中我想从一个PHP的Web服务器,以Android手机获取JSON数据的应用程序。什么我有一个网址,并击中了网址给我,就像
JSON数据 {项目:[{纬度:420,东经:421}]} 。但我想找回我的Andr​​oid手机这个JSON格式和JSON格式获得纬度和经度的值。

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.

我们如何可以得到的Andr​​oid手机..?

how can we get that on android mobile..?

在此先感谢。

推荐答案

首先做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字符串

JSON String

{
"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 "";
    }
}

这篇关于如何获得JSON数据从PHP服务器到Android手机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆