Android PHP Json
我四处看了几个小时,看到的大部分帖子都是很久以前写的,所以可能我就是不明白或者已经过时了。我有两个问题 我有一个Json对象和Json数组,如下所示:Android PHP Json,php,android,arrays,json,object,Php,Android,Arrays,Json,Object,我四处看了几个小时,看到的大部分帖子都是很久以前写的,所以可能我就是不明白或者已经过时了。我有两个问题 我有一个Json对象和Json数组,如下所示: {"command":"update", "Data":["first data","second data","third data","fourth data"]} {"command":"update", "Data":[{"1":"first data"},{"2":"second data"},{"1":"third
{"command":"update", "Data":["first data","second data","third data","fourth data"]}
{"command":"update", "Data":[{"1":"first data"},{"2":"second data"},{"1":"third data"},{"2":"fourth data"}]}
我希望它是这样读的:
{"command":"update", "Data":["first data","second data","third data","fourth data"]}
{"command":"update", "Data":[{"1":"first data"},{"2":"second data"},{"1":"third data"},{"2":"fourth data"}]}
我不清楚如何添加1和2,这样我就可以知道在php端使用什么了。它可能也不是正确的格式,但您会得到一个理想的格式。Android代码:
JSONObject parent = new JSONObject();
JSONArray child = new JSONArray();
child.put("first data");
child.put("second data");
parent.put("Data", child);
php方面的下一个问题是提取数据,以便将其放入数据库,我不确定具体是如何做到的:
// DECODE OUR JSON FROM ANDROID
$data = json_decode(file_get_contents('php://input'), true);
// FOR LOOP TO INSERT DATA INTO DATABASE
for($i=0; $i<count($obj['Data']); $i+=2)
{
// need to get 1 & 2 values to insert into database
//$first = NEED VALUE OF 1
//$second = NEED VALUE OF 2
// mysqli statement to insert into database
$Q = "INSERT INTO `DATA_TABLE` (data1, data2) VALUES ('$first', '$second');
mysqli_query($conn, $Q);
}
//从ANDROID解码我们的JSON
$data=json\u解码(文件\u获取\u内容('php://input",对),;
//FOR循环将数据插入数据库
对于($i=0;$i将代码更改为
JSONObject parent = new JSONObject();
JSONArray child = new JSONArray();
child.put({ "1", "first data" });
child.put({ "2", "second data" });
但我更可能将数据存储为数组中的一个对象,每个对象都是数据库中的一个插入项
JSONObject parent = new JSONObject();
JSONArray child = new JSONArray();
JSONObject item1 = new JSONObject();
JSONObject item2 = new JSONObject();
...
item1.name = "Item 1 name";
item1.rating = "Item 1 rating";
...
child.put(item1);
child.put(item2);
然后,您可以遍历数据数组中的每个项,并知道它包含填充数据库所需的所有数据
JSONObject parent = new JSONObject();
JSONArray child = new JSONArray();
JSONObject item1 = new JSONObject();
JSONObject item2 = new JSONObject();
...
item1.name = "Item 1 name";
item1.rating = "Item 1 rating";
...
child.put(item1);
child.put(item2);