【发布时间】:2019-07-13 04:02:18
【问题描述】:
我正在向我创建的本地 php 服务器发送一些帖子数据。我希望帖子数据采用 json 格式,以便以后从 php 中轻松获取这些数据。
使用Namevaluepairs,我将我的 jsonArray 转换为字符串,并在 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中做这样的事情吗?要做,怎么做? 提前致谢!
【问题讨论】:
-
真的不明白你想要达到什么目的。我得到了什么,您将 dbvalues 转换为 json,然后将其发送到服务器,现在您想要获取该 json 并将其转换回 dbvalues ?
-
@faiizii 我想在php中再次将转换后的字符串解析为json