Parse JSONArray in Android Studio

|▌冷眼眸甩不掉的悲伤 提交于 2021-02-11 12:58:14

问题


I try to get parse an JSONArray from a PHP-Script in AndroidStudio. I get this JSON Response from my PHP script: [{"0":"Firstname","meta_value":"Firstname"},{"0":"Lastname","meta_value":"Lastname"},{"valid":"1"},{"entered":"5"}] Now I try to parse the JSONArray to get the value meta_value so I want to get "Lastname" and "Firstname".

But there must be an error in my code because I get as response: Exception: No value for meta_value

 public class SendPostRequest extends AsyncTask<String, Void, String> {
         String data ="";
         String dataParsed = "";
         String singleParsed ="";

         protected void onPreExecute(){}

         protected String doInBackground(String... arg0) {

             try {

                 URL url = new URL("https://sample.com/code2.php"); // here is your URL path
                 JSONObject postDataParams = new JSONObject();
                 postDataParams.put("sdata", scannedData);
                Log.e("params",postDataParams.toString());

                 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                 conn.setReadTimeout(15000 /* milliseconds */);
                 conn.setConnectTimeout(15000 /* milliseconds */);
                 conn.setRequestMethod("POST");
                 conn.setDoInput(true);
                 conn.setDoOutput(true);

                 OutputStream os = conn.getOutputStream();
                 BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
                 writer.write(getPostDataString(postDataParams));

                 writer.flush();
                 writer.close();
                 os.close();

                 int responseCode=conn.getResponseCode();

                 if (responseCode == HttpsURLConnection.HTTP_OK) {

                     BufferedReader in=new BufferedReader(new
                        InputStreamReader(
                        conn.getInputStream()));

                     StringBuffer sb = new StringBuffer("");
                     String line="";

                     while((line = in.readLine()) != null) {
                    data = data + line;
                    sb.append(line);
                    break;
                     }



                     in.close();

                     JSONArray reader2 = new JSONArray(data);
                     for(int i =0 ;i <reader2.length(); i++){
                    JSONObject JO = (JSONObject) reader2.get(i);
                    singleParsed =  "Name:" + JO.get("meta_value") + "\n";

                    dataParsed = dataParsed + singleParsed +"\n" ;


                }





                return dataParsed;
            }
            else {
                return new String("false : "+responseCode);
            }
        }
        catch(Exception e){
            return new String("Exception: " + e.getMessage());
        }

    }

    @Override
    protected void onPostExecute(String result) {
        Toast.makeText(getApplicationContext(), result,
                Toast.LENGTH_LONG).show();
    }


}

Please dont mark my Answer as duplicate because I searched for 2 weeks and but havent found an Answer! Thank you:)


回答1:


I would suggest you to use GSON for serializing and deserializing your JSON responses. It makes it quite easy to handle then. GSON.

Sample:

new Gson().fromJson("YourJsonHere",JsonElement.class);

Cheers Tarik



来源:https://stackoverflow.com/questions/58342925/parse-jsonarray-in-android-studio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!