Home > other >  How can I Convert JSON to ARRAY Response GET from api Request In Android Java
How can I Convert JSON to ARRAY Response GET from api Request In Android Java

Time:10-06

Here is my api endpoint

I am tring to fetch data and but its show nothing. even when I am trying to print on console same things happend

 JsonObjectRequest jsonRequest = new JsonObjectRequest
            (Request.Method.GET, onewayUrl, null, response -> {


                try {
                    JSONArray jsonArray = new JSONArray(response);

                    for (int i = 0; i < jsonArray.length(); i  ) {

                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        String Career = jsonObject.getString("career");

                        textView = findViewById(R.id.text);
                        textView.setText(Career);

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }, error -> {
                error.printStackTrace();
            });

    Volley.newRequestQueue(AfterSearch.this).add(jsonRequest);
    jsonRequest.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 1, 1.0f));

I got Some error looks like.

W/System.err:     at org.json.JSON.typeMismatch(JSON.java:112)
W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:169)
W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:182)
W/System.err:     at 
com.android.volley.toolbox.JsonObjectRequest.parseNetworkResponse(JsonObjectRequest.java:98)  

CodePudding user response:

Usage of Retrofit is pretty more easy

build.gradle

implementation 'com.google.code.gson:gson:2.9.1'
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'

ApiService.java

public interface ApiService {
  @GET("AirSearch/oneway.php?tripType=oneway&journeyfrom=DAC&journeyto=DXB&departuredate=2022-10-30&adult=1&child=0&infant=0")
  Call<List<Item>> getData();
}

ApiUtil.java

public final class ApiUtil {
    private static Retrofit retrofit;

    private static Retrofit provideRetrofit() {
        if(retrofit != null) {
            return retrofit;
        }
        retrofit = new Retrofit.Builder()
                .baseUrl("https://api.flyfarint.com/v.1.0.0/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        return retrofit;
    }

    public static ApiService getApi() {
        return provideRetrofit().create(ApiService.class);
    }
}

MainActivity.java

private void fetchData() {
    ApiUtil.getApi().getData().enqueue(new Callback<List<Item>>() {
            @Override
            public void onResponse(@NonNull Call<List<Item>> call, @NonNull Response<List<Item>> response) {
                if(response.isSuccessful() && response.body() != null) {
                    List<Item> data = response.body();
                    // data contains parsed json
                }
            }

            @Override
            public void onFailure(@NonNull Call<List<Item>> call, @NonNull Throwable t) {
                Log.e("ApiUtil", t.toString());
            }
        });
}

Item.java

public class Item {
    
    @SerializedName("system")
    @Expose
    public String system;
    @SerializedName("segment")
    @Expose
    public String segment;
    @SerializedName("career")
    @Expose
    public String career;
    @SerializedName("careerName")
    @Expose
    public String careerName;
    @SerializedName("BasePrice")
    @Expose
    public String basePrice;
    @SerializedName("Taxes")
    @Expose
    public String taxes;
    @SerializedName("price")
    @Expose
    public String price;
    @SerializedName("clientPrice")
    @Expose
    public String clientPrice;
    @SerializedName("departure")
    @Expose
    public String departure;
    @SerializedName("departureTime")
    @Expose
    public String departureTime;
    @SerializedName("departureDate")
    @Expose
    public String departureDate;
    @SerializedName("arrival")
    @Expose
    public String arrival;
    @SerializedName("arrivalTime")
    @Expose
    public String arrivalTime;
    @SerializedName("arrivalDate")
    @Expose
    public String arrivalDate;
    @SerializedName("flightduration")
    @Expose
    public String flightduration;
    @SerializedName("bags")
    @Expose
    public String bags;
    @SerializedName("seat")
    @Expose
    public String seat;
    @SerializedName("class")
    @Expose
    public String _class;
    @SerializedName("refundable")
    @Expose
    public String refundable;
    @SerializedName("segments")
    @Expose
    public List<Segment> segments = null;
    @SerializedName("transit")
    @Expose
    public Transit transit;
}

Segment.java

public class Segment  {
    @SerializedName("marketingcareer")
    @Expose
    public String marketingcareer;
    
    @SerializedName("marketingcareerName")
    @Expose
    public String marketingcareerName;
    
    @SerializedName("marketingflight")
    @Expose
    public String marketingflight;
    @SerializedName("operatingcareer")
    @Expose
    public String operatingcareer;
    @SerializedName("operatingflight")
    @Expose
    public String operatingflight;
    @SerializedName("departure")
    @Expose
    public String departure;
    @SerializedName("departureAirport")
    @Expose
    public String departureAirport;
    @SerializedName("departureLocation")
    @Expose
    public String departureLocation;
    @SerializedName("departureTime")
    @Expose
    public Date departureTime;

    @SerializedName("arrival")
    @Expose
    public String arrival;

    @SerializedName("arrivalTime")
    @Expose
    public Date arrivalTime;

    @SerializedName("arrivalAirport")
    @Expose
    public String arrivalAirport;
    @SerializedName("arrivalLocation")
    @Expose
    public String arrivalLocation;
    @SerializedName("flightduration")
    @Expose
    public String flightduration;
    @SerializedName("bookingcode")
    @Expose
    public String bookingcode;
    @SerializedName("seat")
    @Expose
    public String seat;
}

Transit.java

public class Transit {

    public final static long serialVersionUID = 5413373419576714522L;
    @SerializedName("transit1")
    @Expose
    public String transit1;
}

CodePudding user response:

 String url = "https://api.flyfarint.com/v.1.0.0/AirSearch/oneway.php?tripType=oneway&journeyfrom=DAC&journeyto=DXB&departuredate=2022-10-30&adult=1&child=0&infant=0";
    private ProgressDialog pDialog;
   pDialog = new ProgressDialog(this);
        // Showing progress dialog before making http request
        pDialog.setMessage("Loading...");
        pDialog.show();
        RequestQueue queue = Volley.newRequestQueue(MainActivity.this);

        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null, response -> {
            hidePDialog();
            for (int i = 0; i < response.length(); i  ) {

                try {
                    JSONObject responseObj = response.getJSONObject(0); //showing here only one using recyclerview you can show all.USE "i" for all records with model.
                    String careerName = responseObj.getString("careerName");
                    TextView textView=findViewById(R.id.text);
                    textView.setText(careerName);

                } catch (JSONException e) {
                    e.printStackTrace();
                    hidePDialog();
                }
            }
        }, error -> hidePDialog());
        jsonArrayRequest.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 1, 1.0f));
        queue.add(jsonArrayRequest);
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        hidePDialog();
    }

    private void hidePDialog() {
        if (pDialog != null) {
            pDialog.dismiss();
            pDialog = null;
        }
    }
  • Related