0
我想將結果集轉換爲Java中的JSON字符串。該數據的格式爲將結果集轉換爲java中的嵌套json
+---+----------+-------------+---------------+
| id| job_type | question | response_type |
+---+----------+-------------+---------------+
| 1 | quote | question1 | text1 |
| 2 | quote | question2 | number2 |
+---+----------+-------------+---------------+
| 3 | standard | question1 | text2 |
| 4 | standard | question2 | number2 |
+---+----------+-------------+---------------+
,我想在表單,以獲得JSON
{
"JobType": 「Quote",
"Questions": [{
"question": 「question1",
"response_type": 「 text1",
}, {
"question": 「question2",
"response_type": 「 number2",
}],
「JobType」:」Standard」,
"Questions": [{
"question": 「question1",
"response_type": 「 number2",
}, {
"question": 「question2",
"response_type": 「 number2",
}]
}
這是我走到這一步,
JSONObject jobType = new JSONObject();
List<JSONObject> jobTypeQuestionListIndividual = new ArrayList<JSONObject>();
int i = 0;
if (!jobTemplate.next()) {
System.out.println("No records found");
} else {
do {
if (i % 2 == 0) {
jobType.put("JobType",jobTemplate.getString("JobType"));
JSONObject firstQuestion = new JSONObject();
firstQuestion.put("question", jobTemplate.getString("question"));
firstQuestion.put("response_type", jobTemplate.getString("response_type"));
jobTypeQuestionListIndividual.add(firstQuestion);
jobType.put("Questions",jobTypeQuestionListIndividual);
} else {
JSONObject question = new JSONObject();
question.put("question", jobTemplate.getString("question"));
question.put("response_type", jobTemplate.getString("response_type"));
jobTypeQuestionListIndividual.add(question);
}
i = i+1;
} while (jobTemplate.next());
}
System.out.println(jobType);
但這會導致
{
"JobType": 「Quote",
"Questions": [{
"question": 「question1",
"response_type": 「 text1",
}, {
"question": 「question2",
"response_type": 「 number2",
},{
"question": 「question1",
"response_type": 「 number2",
}, {
"question": 「question2",
"response_type": 「 number2",
}]
}
在此先感謝您的幫助頁。
我從來沒有使用JSON與Java,但我建議你應該創建一個QuestioResponse只有兩個字符串的類(如果你想保持ID,也許是一個整數),以及一個包含QuestionResponse列表的類JobType(使用一個保存順序的列表,如果它很重要)以及帶jobtype名稱的String。然後,一旦您將這些Beans中的所有結果集都轉換成了,您就可以使用它們來創建一個Json對象(或者甚至使用一些可以爲您做的API /庫)。這應該更容易。 – Asoub