Skip to content
Advertisement

How to parse JSON data without define array in JSON in Android Studio

I am new in Android I am trying to develop an application which is used to validate ifsc code by entering code in edit text.

So in this project, I am using Razorpay JSON to fetch data but when I fetch data it shows in JSON format not readable format.

How to convert JSON data in a readable format?

My code works fine when I am adding square bracket [] in JSON but I can’t edit JSON because it is third-party JSON.

Here is my code:

public class fetchdata extends AsyncTask<Void,Void,Void> {
    String data = "";
    String dataprart ;
    String singlePared = "";
    String datamanner = "";

    @Override
    protected Void doInBackground(Void... voids) {
        dataprart=ifsccode.getText().toString();
        String urls="https://ifsc.razorpay.com/"+dataprart;

        try {
            URL url = new URL(urls);
            HttpURLConnection httpURLConnection = (HttpURLConnection) 
            url.openConnection();

            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new 
            InputStreamReader(inputStream));

            String line = "";
            while (line != null) {
                line = bufferedReader.readLine();
                data= data + line;
            }

            JSONArray JA = new JSONArray(data);
            for ( int i = 0; i<JA.length(); i++) {
                JSONObject JO = (JSONObject) JA.get(i);

                singlePared =
                    "BRANCH  --- " + JO.get("BRANCH") + "n"+"n"+
                    "STATE   ---" + JO.get("STATE") + "n"+"n"+
                    "DISTRICT ---" + JO.get("DISTRICT") + "n"+"n"+
                    "ADDRESS  --- " + JO.get("ADDRESS") + "n"+"n"+
                    "CITY  ---" + JO.get("CITY") + "n"+"n"+
                    "BANK   ---" + JO.get("BANK") + "n";

                    datamanner = datamanner +singlePared;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        IFSc_validate.ifsc.setText(datamanner);
        super.onPostExecute(aVoid);
    }
}

Advertisement

Answer

This is happening because the response is a JSONObject and not a JSONArray.

Try these changes

        JSONObject JO = new JSONObject(data);
        singlePared = //continue        

Remove the for loop and the JSONArray declaration


Also you should consider using volley to get an JSONObject response it would make life easier.

How to get and parse a JSON-object with Volley

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement