Android 如何从ArrayList创建JSONObject<;对象>;提出邮寄要求?

Android 如何从ArrayList创建JSONObject<;对象>;提出邮寄要求?,android,json,Android,Json,我正在尝试使用JSONObject作为请求将数据发布到服务器中。我不知道如何使用以下类型的数据从ArrayList创建JSONObject {"AnswersList":[ { "questionID": 1, "question": "What is yout name?", "questionType": "STRI", "ques

我正在尝试使用JSONObject作为请求将数据发布到服务器中。我不知道如何使用以下类型的数据从ArrayList创建JSONObject

{"AnswersList":[
{
    "questionID": 1,
    "question": "What is yout name?",
    "questionType": "STRI",
    "questionOrder": 1,
    "answer":"Avishek",
    "choiceList": []
},
{
    "questionID": 2,
    "question": "Sports?",
    "questionType": "MULT",
    "questionOrder": 2,
     "answer":"1,2",
    "choiceList": [
        {
            "choiceID": 1,
            "choiceName": "Football",
            "choiceOrder": 1
        },
        {
            "choiceID": 2,
            "choiceName": "Basketball",
            "choiceOrder": 2
        }
    ]
}]}
谁能帮我解决这个问题。 我创建了两个模型类来处理JSON。第一个是Question.java,第二个是Choice.java

public class Choice {

@SerializedName("choiceID")
private String choiceID;

@SerializedName("choiceName")
private String choiceName;

@SerializedName("choiceOrder")
private String choiceOrder;


//getter and setter method
}
模型类包括: Question.java

public class Question {

@SerializedName("questionID")
public String questionID;
@SerializedName("question")
public String question;
@SerializedName("questionType")
public String questionType;
@SerializedName("questionOrder")
public String questionOrder;
@SerializedName("answer")
public String answer;
@SerializedName("choiceList")
public ArrayList<Choice> choices = new ArrayList<>();
@SerializedName("isRequired")
public boolean isRequired;


//getter and setter methods
}
我尝试过这个代码,但没有成功

    DatabaseHelper databaseHelper = new DatabaseHelper(mContext);
    ArrayList<Question> questionsAnswer = new ArrayList<>();
    questionsAnswer.addAll(databaseHelper.getQuestionList());

    Log.v(TAG, "size of question answer list : " + questionsAnswer.size());

    Map<String, Object> jsonParams = new ArrayMap<>();
    //put something inside the map, could be null
    JSONArray jsArray = new JSONArray(questionsAnswer);
    jsonParams.put("AnswersList", jsArray);
DatabaseHelper-DatabaseHelper=newdatabasehelper(mContext);
ArrayList questionsAnswer=新的ArrayList();
questionsAnswer.addAll(databaseHelper.getQuestionList());
Log.v(标签,“问题答案列表的大小:”+questionsAnswer.size());
Map jsonParams=newarraymap();
//将某些内容放入地图中,可能为空
JSONArray jsArray=新JSONArray(问题回答);
jsonParams.put(“应答列表”,jsArray);

首先,我建议对请求使用改装库()

要从对象创建json字符串,可以使用Gson库

Gson gson = new Gson();
String jsonInString = gson.toJson(obj);
更新 别忘了在gradle文件中添加Gson依赖项

dependencies {
  implementation 'com.google.code.gson:gson:2.8.6'
}

在Java上解析JSON对象和数组我们应该使用GSON

添加渐变文件:


实现'com.google.code.gson:gson:2.8.2'

不,先生,请稍等,我正在更新我已经完成的代码。先生,您能检查一下我已经完成的代码吗。我只想从ArrayList创建JSONObject,以便将此JSONObject发布到服务器中