我正在向我创建的本地php服务器发送一些发布数据。我希望发布数据为json格式,以便以后从php轻松进行提取。
使用Namevaluepairs
,我将jsonArray转换为String并在php中的文本文件中获得以下结果:
[{"name":"Relojes 2018 Watch Men LIGE Fashion Sport","price":"US $18.19"},{"name":"Relojes 2018 Watch Men LIGE Fashion Sport","price":"US $18.19"},{"name":"Relojes 2018 Watch Men LIGE Fashion Sport","price":"US $18.19"}]
在android studio中,我有一些代码将内容格式化为json,然后以字符串形式:
private void postData() {
try {
String postReceiverUrl = "http://192.168.1.104/bot/post.php";
Log.v(TAG, "postURL: " + postReceiverUrl);
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(postReceiverUrl);
List<NameValuePair> nameValuePairs = new ArrayList();
DatabaseHandler db = new DatabaseHandler(this);
db.openDB();
Cursor c = db.getAllDatas();
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
while (c.moveToNext()) {
String name = c.getString(1);
String price = c.getString(2);
//nameValuePairs.add(new BasicNameValuePair("name", name));
//nameValuePairs.add(new BasicNameValuePair("price", price));
jsonObject.put("name", name);
jsonObject.put("price", price);
jsonArray.put(jsonObject);
//httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//HttpResponse response = httpClient.execute(httpPost);
}
//System.out.println("jsonObj" + jsonArray.toString());
//StringEntity se = new StringEntity( jsonObject.toString());
//se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
//httpPost.setEntity(se);
nameValuePairs.add(new BasicNameValuePair("data", jsonArray.toString()));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
在我的接收器php代码中:
<?php
$name=$_POST["data"];
//$price = $_POST["price"];
//$result = '<br>' . $name . ' ' . $price;
$result = $name;
$filename="submitted-msg.txt";
file_put_contents($filename,$result,FILE_APPEND);
$androidmessages=file_get_contents($filename);
echo $androidmessages;
?>
现在我的疑问是,我可以像以前一样将字符串转换为json数组吗?或者有可能在php中做类似的事情?要这样做,怎么做? 预先感谢!
答案 0 :(得分:1)
使用带有'JSON_UNESCAPED_SLASHES'标志的json_encode删除反斜杠。
json_encode($androidmessages, JSON_UNESCAPED_SLASHES);
或者您也可以使用stripslashes
stripslashes(json_encode($androidmessages));
您将获得响应json格式。
[{"name":"Relojes 2018 Watch Men LIGE Fashion Sport","price":"US $18.19"},{"name":"Relojes 2018 Watch Men LIGE Fashion Sport","price":"US $18.19"},{"name":"Relojes 2018 Watch Men LIGE Fashion Sport","price":"US $18.19"}]
答案 1 :(得分:0)
尝试一下:
echo json_encode($androidmessages);