栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用JSON将ArrayList从Android发送到PHP脚本

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用JSON将ArrayList从Android发送到PHP脚本

这是您的数组:您可以根据需要在示例中创建更多数组。

ArrayList<String> contact = new ArrayList<String>();

然后,创建JSONObject类型的JSONcontacts变量以将此数组存储在此对象中

JSonObject JSoncontacts = new JSonObject();

现在,遍历该联系人数组中的所有元素并将其存储在JSONcontacts中

//Loop through array of contacts and put them to a JSoncontact objectfor (int i = 0; i < contact.size(); i++) {    try {        JSONcontacts.put("Count:" + String.valueOf(i + 1), contact.get(i));    } catch (JSonException e) {        e.printStackTrace();    }}

假设您创建了许多您可能已经完成的数组,现在您必须将它们全部放入1个JSON中。因此,创建类型为JSONObject()的EverythingJSON变量

JSonObject EverythingJSON = new JSonObject();

然后将所有联系人数组和其他数组放入其中,就可以按照上述方法遍历它们:

EverythingJSON.put("contact", JSONcontacts);EverythingJSON.put("something", JSONsoemthing);EverythingJSON.put("else", JSONelse);

现在,这是将其发送到您的PHP服务器的AsynchTask:

new AsyncTask() {    //String responseBody = "";    @SuppressWarnings("unused")    protected void onPostExecute(String msg) {        //Not Needed    }    protected Object doInBackground(Object... params) {        //Create Array of Post Variabels        ArrayList<NamevaluePair> postVars = new ArrayList<NamevaluePair>();        //Add a 1st Post Value called JSON with String value of JSON inside        //This is first and last post value sent because server side will depre the JSON and get other vars from it.        postVars.add(new BasicNamevaluePair("JSON", EverythingJSON.toString());        //Declare and Initialize Http Clients and Http Posts        HttpClient httpclient = new DefaultHttpClient();        HttpPost httppost = new HttpPost(Config.OnlineAPI);        //Format it to be sent        try { httppost.setEntity(new UrlEnpredFormEntity(postVars));        } catch (UnsupportedEncodingException e) { e.printStackTrace();        }              try { HttpResponse response = httpclient.execute(httppost); String responseBody = EntityUtils.toString(response.getEntity());        } catch (ClientProtocolException e) { e.printStackTrace(); Log.v("MAD", "Error sending... ");        } catch (IOException e) { e.printStackTrace(); Log.v("MAD", "Error sending... ");        }        return null;    }}.execute(null, null, null);

现在在PHP服务器端,您可以像这样循环遍历此JSON:首先,从POST获取该JSON并将其存储在var中:

//Receive JSON$JSON_Received = $_POST["JSON"];

现在从JSON解码:

//Depre Json$obj = json_depre($JSON_Received, true);

这是遍历联系人数组并从中获取键和值的循环:

foreach ($obj['contact'] as $key => $value) {    //echo "<br>------" . $key . " => " . $value;}

您可以对发送的其他数组重复此循环:)祝您好运!



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/385852.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号