简体   繁体   中英

How To Extract elements from a list of objects and store in String array

I am trying to get a response from the server and show it in a spinner.My Server returns a response that contains a JSON array. The JSON Array has two fields question and q_id I want to store both the data in a different string array and want to populate spinner with details from question and by using the index of the question selected from spinner I want to get the elements from q_id array and send to server

thank you.

Server Response

 {
    "data": [ 
        {
            "q_id": "21",
            "question": "Flipkart VS Amazone which is better?"
        },
        {
            "q_id": "22",
            "question": "Test"
        },

    ],
    "status": true,
    "message": "Bank Ac created sucessfully"}

Model For this response

 public class Question {

    @SerializedName("data")
    @Expose
    private List<Datum> data = null;
    @SerializedName("status")
    @Expose
    private Boolean status;
    @SerializedName("message")
    @Expose
    private String message;

    public List<Datum> getData() {
        return data;
    }

    public void setData(List<Datum> data) {
        this.data = data;
    }

    public Boolean getStatus() {
        return status;
    }

    public void setStatus(Boolean status) {
        this.status = status;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

}

Datum Class

    public class Datum {

    @SerializedName("q_id")
    @Expose
    private String qId;
    @SerializedName("question")
    @Expose
    private String question;

    public String getQId() {
        return qId;
    }

    public void setQId(String qId) {
        this.qId = qId;
    }

    public String getQuestion() {
        return question;
    }

    public void setQuestion(String question) {
        this.question = question;
    }

}

Call To Server

private void getQuestions() {
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient client = new OkHttpClient.Builder().readTimeout(30, TimeUnit.SECONDS).writeTimeout(30, TimeUnit.SECONDS).addInterceptor(interceptor).build();
    if (retrofit == null) {
        retrofit = new Retrofit.Builder()
                .baseUrl(CommonObjects.BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    getquestion Service = retrofit.create(getquestion.class);

    Call<Question> call = Service.post(id);

    call.enqueue(new Callback<Question>() {
        @Override
        public void onResponse(Call<Question> call, Response<Question> response) {
            if (!response.body().getStatus()) {
                message = response.body().getMessage();
                showMessage(message);
            } else {
                Question jsonResponse = response.body();
                message = response.body().getMessage();
                CommonObjects.q.setData(jsonResponse.getData());
                CommonObjects.q.setMessage(message);
                CommonObjects.q.setStatus(response.body().getStatus());
            }
        }


        @Override
        public void onFailure(Call<Question> call, Throwable t) {
            // handle execution failures like no internet connectivity
            BusProvider.getInstance().post(new ErrorEvent(-2, t.getMessage()));
        }
    });

}

Interface

    public interface getquestion {
    @FormUrlEncoded
    @POST("feedback_question")
    Call<Question> post(
            @Field("userid") String question
    );
}

You need JSONObject and JSONArray classes.

Steps to parse JSON response from server.

  1. Instantiate JSONObject class and pass the variable containing JSON response into the constructor of the JSONObject class.

     JSONObject jsonObj = new JSONObject(jsonResponse); 
  2. Now you can get anything in JSON response using methods available in JSONObject class.

for example if you need data array, to extract it, you can use getJSONArray method and pass in the key of the array which in your case is data

JSONArray arr = jsonObj.getJSONArray("data");

now to extract data in data array, use an appropriate method available in JSONArray class.

similarly you can extract other data using JSONObject and JSONArray classes.

Just keep in mind, if you have a JSON object, use methods available in JSONObject class and if you have JSON array, use methods available in JSONArray class to extract desired data.

You can use org.json library to extract that JSON like this:

JSONObject jsonObject = new JSONObject(serverResponse);
JSONArray jsonArray = jsonObject.getJSONArray("data");
ArrayList<String> qids = new ArrayList<>();
ArrayList<String> questions = new ArrayList<>();

for (int i=0; i<jsonArray.length(); i++) {
   JSONObject item = jsonArray.get(i);
   qids.add(item.getString("q_id"));
   questions.add(item.getString("question"));
}

Use this type of code for parsing Json array. For more examples

JSONObject jsonObj = new JSONObject(jsonResponse);
JSONArray data = jsonObj.getJSONArray("data");

Question question = new Question();
List<Datum> datumList = new ArrayList<Datum>();

          if (data != null) {
          for (int i = 0; i < data.length(); i++) {
              try {
                    JSONObject obj = (JSONObject) data.get(i);
                    Datum datum = new Datum();
                    datum.setQId(data.getString("q_id"));
                    datum.setQuestion(data.getString("question"));
                    datumList.add(datum);                        

                 } catch (Exception e) {
                     e.printStackTrace();
                 }
              }
            }
      question.setData(datumList);

For more detail and learn

use for each loop and fill data in your arraylist. Do something like this.

else {
    ArrayList<String> QidList = new ArrayList<String>();
    ArrayList<String> QuestionList = new ArrayList<String>();
    Question jsonResponse = response.body();
    message = response.body().getMessage();
    CommonObjects.q.setData(jsonResponse.getData());
    CommonObjects.q.setMessage(message);
    CommonObjects.q.setStatus(response.body().getStatus());
    for (Datum data : jsonResponse.getData()) {
        if((!TextUtils.isEmpty(data.getQId())) && 
                      (!TextUtils.isEmpty(data.getQuestion()))){
             QidList.add(data.getQId());
             QuestionList.add(data.getQuestion());
        }

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM