简体   繁体   English

如何从对象列表中提取元素并存储在String数组中

[英]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. 我正在尝试从服务器获取响应并将其显示在微调器中。我的服务器返回的响应包含JSON数组。 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 JSON数组具有两个字段questionq_id,我想将数据都存储在不同的字符串数组中,并想用问题的详细信息填充微调器,并使用从微调器中选择的问题的索引,我想从q_id数组中获取元素并发送到服务器

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. 您需要JSONObjectJSONArray类。

Steps to parse JSON response from server. 解析来自服务器的JSON响应的步骤。

  1. Instantiate JSONObject class and pass the variable containing JSON response into the constructor of the JSONObject class. 实例化JSONObject类,然后将包含JSON响应的变量传递到JSONObject类的构造函数中。

     JSONObject jsonObj = new JSONObject(jsonResponse); 
  2. Now you can get anything in JSON response using methods available in JSONObject class. 现在,您可以使用JSONObject类中可用的方法在JSON响应中获取任何内容。

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 例如,如果您需要data数组以提取它,则可以使用getJSONArray方法并传入该数组的键(在您的情况下为data

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

now to extract data in data array, use an appropriate method available in JSONArray class. 现在要提取数据数组中的data ,请使用JSONArray类中可用的适当方法。

similarly you can extract other data using JSONObject and JSONArray classes. 同样,您可以使用JSONObjectJSONArray类提取其他数据。

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. 请记住,如果您有JSON对象,请使用JSONObject类中可用的方法,如果您有JSON数组,请使用JSONArray类中可用的方法来提取所需的数据。

You can use org.json library to extract that JSON like this: 您可以像这样使用org.json库提取该JSON:

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. 使用此类代码来解析Json数组。 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. 用于每个循环并在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());
        }

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从列表中提取String []元素 - Extract String[] elements from a list 如何从对象列表中提取K个“最小”元素? - How do I extract the K “smallest” elements from a list of objects? (Java)如何将列表中的选定元素存储到数组中 - (Java) How to store selected elements from a list into array 从列表字符串存储到另一个数组列表 - store from list string to another array list 如何使用构造函数初始化每个数组元素时从文件读取和存储对象数组 - How to read from file and store array of objects while initializing each array elements using a constructor 如何在java中存储和读取对象的数组列表? - How to store and read an array list of objects in java? (Java)如何从列表中以字符串或字符串数​​组返回对象? - (Java) How to return objects from a list as a string or array of strings? 我有一个包含多个 JSON 对象的数据字符串,如何将字符串中的所有 JSON 对象存储在一个充满对象的数组中? - I have a data String with multiple JSON Objects, how can I store all JSON Objects from the String in an Array filled with objects? 如何从Java中的对象数组列表中获取字符串? - How to get an a String from an array list of objects in java? 如何从字符串中提取所有整数并将它们存储在java中的int数组中 - How to extract all integers from a string and store them in an int array in java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM