JSON在php中的迭代,使用由Java/Android发送的数据。

huangapple go评论88阅读模式
英文:

JSON iteration in php using data sent by java/android

问题

从我的Android设备发送到我的PHP服务器的JSON如下:

{
  "class": "SURESHOT",
  "subject": "Maths",
  "qstn": "[607421_15958169393.JPG, 410816_15958169444.JPG, 
          655502_15958169495.JPG, 625421_15958179086.JPG, 
          625421_15958179086.JPG, 461984_15958180457.JPG]",
  "ans": "[C, B, A, D, C, C]",
  "lickey": "jg2ler3xvbdgsjkru12tutujghgjgl4jkjojuir8uttzcdadasretf",
  "user": "1000",
  "result": "[fail, fail, pass, fail, fail, fail]",
  "qid": "[37, 38, 39, 40, 40, 41]"
}

现在在PHP中无法正确迭代数据,其中'qstn'、'ans'和'result'是有问题的部分。我们该如何正确处理它们?

我使用了以下代码进行初步数据转换:json_encode(($_POST), true);

这是我用于获取JSON的代码:

reqPostanswers = new StringRequest(Request.Method.POST, urll, new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        //Log.i("posting info :", response.toString());
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        //Log.i("posting error  :", error.toString());
    }
}) {

    @Override
    protected Map<String, String> getParams() {
        Map<String, String> params = new HashMap<String, String>();
        params.put("subject", subject);
        params.put("class", qSet[qsetCntr][0]);
        params.put("user", thisuser);
        params.put("result", resltn.toString());
        params.put("qstn", qstnn.toString());
        params.put("qid", qiddn.toString());
        params.put("ans", answn.toString());
        params.put("lickey", "jg2ler3xvbdgsjkru12tutujghgjgl4jkjojuir8uttzcdadasretf");

        return params;
    }

};
answerpostQueue = Volley.newRequestQueue(getApplicationContext());
answerpostQueue.add(reqPostanswers);

参数设置中的数组或变量是ArrayLists。

英文:

From my android my PHP sever is receiving the below json :

{
  &quot;class&quot;:&quot;SURESHOT&quot;,
  &quot;subject&quot;:&quot;Maths&quot;,
  &quot;qstn&quot;:&quot;[607421_15958169393.JPG, 410816_15958169444.JPG, 
          655502_15958169495.JPG,   625421_15958179086.JPG, 
          625421_15958179086.JPG, 461984_15958180457.JPG]&quot;,
  &quot;ans&quot;:&quot;[C, B, A, D, C, C]&quot;,
  &quot;lickey&quot;:&quot;jg2ler3xvbdgsjkru12tutujghgjgl4jkjojuir8uttzcdadasretf&quot;,
  &quot;user&quot;:&quot;1000&quot;,
  &quot;result&quot;:&quot;[fail,fail, pass, fail, fail, fail]&quot;,
  &quot;qid&quot;:&quot;[37, 38, 39, 40, 40, 41]&quot;
 }

Now iterating through the data is not possible in PHP. 'qstn', 'ans' and 'result' are the problematic ones. How can we do it properly?

I used json_encode(($_POST),true); for preliminary data conversion.

This is the code I run to get the JSON:

This is the code from I get json.

   reqPostanswers = new StringRequest(Request.Method.POST, urll,new  Response.Listener&lt;String&gt;() {
        @Override
        public void onResponse(String response) {
            //Log.i(&quot;posting info :&quot;,response.toString());
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            //Log.i(&quot;posting error  :&quot;,error.toString());
        }
    }){

        @Override
        protected Map&lt;String,String&gt; getParams(){
            Map&lt;String,String&gt; params = new HashMap&lt;String, String&gt;();
            params.put(&quot;subject&quot;,subject);
            params.put(&quot;class&quot;,qSet[qsetCntr][0]);
            params.put(&quot;user&quot;, thisuser);
            params.put(&quot;result&quot;,resltn.toString());
            params.put(&quot;qstn&quot;,qstnn.toString());
            params.put(&quot;qid&quot;, qiddn.toString());
            params.put(&quot;ans&quot;,answn.toString());
            params.put(&quot;lickey&quot;,&quot;jg2ler3xvbdgsjkru12tutujghgjgl4jkjojuir8uttzcdadasretf&quot;);

            return params;
        }

    };
    answerpostQueue = Volley.newRequestQueue(getApplicationContext());
    answerpostQueue.add(reqPostanswers);

The arrays or variables in the prams set up is Arraylists only.

答案1

得分: 1

首先,问题出在您创建的 JSON 上。JSON 数组应如下所示:

"qstn": ["607421_15958169393.JPG","410816_15958169444.JPG",
          "655502_15958169495.JPG","625421_15958179086.JPG","625421_15958179086.JPG",
          "461984_15958180457.JPG"]

请按照上述方式转换您的 JSON 数组,在 PHP 部分使用以下代码:

$model = json_decode($json,true);

现在,您可以按照以下方式从这个变量中访问值:

$class = $model["class"];
// 可以访问 qstn 数组的第 0 个索引
$qsnt1 = $model["qstn"][0];

为了将来避免这类错误,建议使用 gson 来为您创建 JSON。

英文:

first of all the problem is with your created json. Json array should be as shown below ,

&quot;qstn&quot;: [&quot;607421_15958169393.JPG&quot;,&quot;410816_15958169444.JPG&quot;,
      &quot;655502_15958169495.JPG&quot;,&quot;625421_15958179086.JPG&quot;,&quot;625421_15958179086.JPG&quot;, 
&quot;461984_15958180457.JPG&quot;]

Convert your json array in the manner shown above and in php side use ,

$model = json_decode($json,true);

Now u can access the values from this variable as following:

 $class = $model[&quot;class&quot;];
 //The 0th index of qstn array can be accessed as
 $qsnt1 = $model[&quot;qstn&quot;][0];

For saving yourself from such errors in future use gson to create json for you.

答案2

得分: 1

Android代码实际上没有向服务器发送JSON。它使用的是旧的键值对表单格式,无法表示复杂对象。要修复这个问题,请将Android代码更改为使用JsonObjectRequest而不是StringRequest,并将请求传递为JSONObject

JSONObject params = new JSONObject();
params.put("subject", subject);
params.put("class", qSet[qsetCntr][0]);
params.put("user", thisuser);
params.put("result", new JSONArray(resltn));
params.put("qstn", new JSONArray(qstnn));
params.put("qid", new JSONArray(qiddn));
params.put("ans", new JSONArray(answn));
params.put("lickey", "jg2ler3xvbdgsjkru12tutujghgjgl4jkjojuir8uttzcdadasretf");

reqPostanswers = new JsonObjectRequest(Request.Method.POST, urll, params,
    new Response.Listener<String>() { ... },
    new Response.ErrorListener() { ... }
});

完成这个更改后,您可能需要更改PHP代码,以便它从请求正文中读取JSON。如何做到这一点在这里有解释:https://www.geeksforgeeks.org/how-to-receive-json-post-with-php/

英文:

The Android code is not actually sending JSON to the server. It's using the old key-value form field format, which does not have a way to represent complex objects. To fix this, change the Android code to use JsonObjectRequest instead of StringRequest, and pass the request in as a JSONObject:

JSONObject params = new JSONObject();
params.put(&quot;subject&quot;,subject);
params.put(&quot;class&quot;,qSet[qsetCntr][0]);
params.put(&quot;user&quot;, thisuser);
params.put(&quot;result&quot;, new JSONArray(resltn));
params.put(&quot;qstn&quot;, new JSONArray(qstnn));
params.put(&quot;qid&quot;, new JSONArray(qiddn));
params.put(&quot;ans&quot;, new JSONArray(answn));
params.put(&quot;lickey&quot;,&quot;jg2ler3xvbdgsjkru12tutujghgjgl4jkjojuir8uttzcdadasretf&quot;);

reqPostanswers = new JsonObjectRequest(Request.Method.POST, urll, params,
    new  Response.Listener&lt;String&gt;() { ... },
    new Response.ErrorListener() { ... }
});

After you have done this change, you most likely have to change your PHP code too, so that it reads JSON from the request body. How to do that is explained for example here: https://www.geeksforgeeks.org/how-to-receive-json-post-with-php/

答案3

得分: 0

使用 ltrimrtrim 函数从字符串中删除 [],然后使用 explode 将字符串转换为数组。
注意:此示例仅在分隔符为 , 和空格 (&quot;, &quot;) 时有效。

示例使用 &quot;qstn&quot;

$array = json_decode($json, true);

$resultArray = explode(", ", rtrim(ltrim($array["qstn"],"["),"]"));

var_dump($resultArray);
英文:

using ltrim and rtrim functions to delete the [ and ] from the string, then with explode you can convert the string into array.
NB: this exemple only work when the delimiter is , and blank space (&quot;, &quot;)

exemple with &quot;qstn&quot;:

$array = json_decode($json, true);

$resultArray = explode(&quot;, &quot;,rtrim(ltrim($array[&quot;qstn&quot;],&quot;[&quot;),&quot;]&quot;));

var_dump($resultArray);

huangapple
  • 本文由 发表于 2020年8月10日 02:21:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/63329833.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定