我有以下代码。此代码将包含对象列表的对象列表转换为json格式。
package com.fg.test;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Test {
public static void main(String[] args) {
Question question = new Question();
JSONArray array = new JSONArray();
question.setQuestionId("1");
question.setQuestionText("hello");
Options option1 = new Options();
option1.setOption1("1");
option1.setAnswer("0");
Options option2 = new Options();
option2.setOption1("2");
option2.setAnswer("0");
Options option3 = new Options();
option3.setOption1("3");
option3.setAnswer("0");
Options option4 = new Options();
option4.setOption1("4");
option4.setAnswer("1");
List<Options> options = new ArrayList<Options>();
options.add(option1);
options.add(option2);
options.add(option3);
options.add(option4);
question.setOptions(options);
Question newQuestion = null;
try {
newQuestion =(Question) question.clone();
} catch (CloneNotSupportedException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
List<Question> questions = new ArrayList<Question>();
questions.add(question);
questions.add(newQuestion);
for(Question ques: questions){
JSONObject obj = new JSONObject();
try {
obj.put("question", ques.getQuestionText());
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
array.put(obj);
for (Options op : ques.getOptions())
{
JSONObject obj1 = new JSONObject();
try {
obj1.put("option", op.getOption1());
//obj.put("answer", op.getAnswer());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
array.put(obj1);
}
}
System.out.println(array);
}
}
我收到以下格式的输出..
[{"question":"Who invented java ?"},{"option":"Charles babbage"},{"option":"james gosling"},{"option":"gavin king"},{"option":"dennis richie"},{"question":"What is java ?"},{"option":"OOPs"},{"option":"koops"},{"option":"joops"},{"option":"gaps"}]
但是,我需要以下格式的这个json ..
[{"question":"Who invented java ?","option":"Charles babbage","option":"james gosling","option":"gavin king","option":"dennis richie"},{"question":"What is java ?","option":"OOPs","option":"koops","option":"joops","option":"gaps"}]
我怎样才能做到这一点?任何想法?
答案 0 :(得分:0)
我已经尝试了一些东西,我在下面的代码中得到了上面提到的输出。
scalatest