Как я должен получить данные из sourceJson в Android с помощью volley?

#android #json #android-studio #android-volley

#Android #json #android-studio #android-volley

Вопрос:

Ниже приведен ответ, который я получаю, я хочу получить данные из «SourceJson», но не могу понять, почему я получаю «» в исходном json, пожалуйста, помогите мне

 {
    "incomingOrder": [
        {
            "Namw": 8510,
            "Surname": "00",
            "mob": "00",
            "phone": "000",
            "SourceJson": "{"cart_gst":30.21,"instructions":"","order_packing_charges":30,"cart_igst_percent":0,"cart_sgst":15.1038,}",
            "test": "NotSynced",
            "test": "DPA",
}]}
  

Ответ №1:

Попробуйте этот код :

 requestQueue = Volley.newRequestQueue(this);
        JsonObjectRequest obreq = new JsonObjectRequest(Request.Method.GET, JsonURL,
                // The third parameter Listener overrides the method onResponse() and passes
                //JSONObject as a parameter
                new Response.Listener<JSONObject>() {

                    // Takes the response from the JSON request
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            JSONArray jsonArray = response.getJSONArray("incomingOrder");

                            JSONObject jsonObject = jsonArray.getJSONObject(0);

                            JSONObject objSourceJson=jsonObject.getJSONObject("SourceJson");

                            Log.i("IvaSourceJson",objSourceJson.toString());

                            String cart_gst=objSourceJson.getString("cart_gst");
                            String instructions=objSourceJson.getString("instructions");
                        }
                        // Try and catch are included to handle any errors due to JSON
                        catch (JSONException e) {
                            // If an error occurs, this prints the error to the log
                            e.printStackTrace();
                        }
                    }
                },
                // The final parameter overrides the method onErrorResponse() and passes VolleyError
                //as a parameter
                new Response.ErrorListener() {
                    @Override
                    // Handles errors that occur due to Volley
                    public void onErrorResponse(VolleyError error) {
                        Log.e("Volley", "Error");
                    }
                }
        );
        // Adds the JSON object request "obreq" to the request queue
        requestQueue.add(obreq);
  

Комментарии:

1. получение ошибки «SourceJson типа java.lang. Строка не может быть преобразована в JSONObject »

2. «SourceJson»: «{«cart_gst»:30.21,»instructions»:»»,»order_packing_charges»:30,»cart_igst_percent»:0,»cart_sgst»:15.1038,}»

3. Извините, но я этого не понял

4. Этот SourceJson также является строкой, поэтому вы должны разобрать эту строку в json. Используйте анализатор Json

5. Также это недопустимый Json. наконец, перед закрытием пайки есть запятая (,). Сначала попробуйте получить действительный Json.

Ответ №2:

Поскольку данные JSONArray имеют тип списка, их лучше не использовать jsonArray.getJSONObject(0); .
Используйте этот код для получения нескольких результатов,

 StringRequest request = new StringRequest(Request.Method.GET, "", new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.d("Response", response);
            try {
                JSONObject object = new JSONObject(response);

                JSONArray array = object.getJSONArray("incomingOrder");
                for (int i = 0; i < array.length(); i  ){
                    JSONObject object1 = array.getJSONObject(i);
                    String name = object1.getString("Namw");
                    String surname = object1.getString("Surname");
                    String mob = object1.getString("mob");
                    String phone = object1.getString("phone");
                    String sourceJson = object1.getString("SourceJson");
                    String test = object1.getString("test");
                    String test1 = object1.getString("test");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d("Error", error.getMessage());
        }
    });
    Context context;
    RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
    queue.add(request);  
  

Закодируйте это в любом методе и вызовите метод, в котором требуется действие.