毕业设计中使用到了集合(List)和json之间的互相转换,整理记录如下:
首先给出bean中包含的相关属性:
public class FillInQuestionsBean
{
private int questionId;
private String questionBody;
private String questionAnswer;
private String question_property; //20180415 新增题目分类属性 用于数据分析
public void setId(int id)
{
questionId = id;
}
public void setBody(String body)
{
questionBody = body;
}
public void setAnswer(String answer)
{
questionAnswer = answer;
}
public void setQuestionProperty(String property)
{
question_property = property;
}
public int getId()
{
return questionId;
}
public String getBody()
{
return questionBody;
}
public String getAnswer()
{
return questionAnswer;
}
public String getQuestionProperty()
{
return question_property;
}
}
---------------------------------------------------------------------------------------------------------------------------------
将集合转换为json:
需要以下依赖:
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
具体函数:
//将填空题集合转换成JSONArray
public static JSONArray fillInQuestionListToJson(ArrayList<FillInQuestionsBean> List)
{
JSONArray json = new JSONArray();
for(FillInQuestionsBean Bean : List)
{
JSONObject jo = new JSONObject();
jo.put("id", Bean.getId());
jo.put("body", Bean.getBody());
jo.put("answer", Bean.getAnswer());
jo.put("question_property", Bean.getQuestionProperty()); //20180415
json.add(jo);
}
return json;
}
---------------------------------------------------------------------------------------------------------------------------------
将相应的json转换为集合:
需要以下依赖:
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
具体函数:
//将填空题JSONArray转为填空题集合
public static ArrayList<OnlineFillQuestionBean> fillInQuestionJSONToArray(String json_string) throws JSONException
{
JSONArray json = new JSONArray(json_string);
ArrayList<OnlineFillQuestionBean> List = new ArrayList<OnlineFillQuestionBean>();
if(json.length() > 0)
{
for(int i = 0;i < json.length();i++)
{
JSONObject job = json.getJSONObject(i);
OnlineFillQuestionBean Bean = new OnlineFillQuestionBean();
Bean.setId(job.getInt("id"));
Bean.setBody(job.getString("body"));
Bean.setAnswer(job.getString("answer"));
Bean.setQuestionProperty(job.getString("question_property")); //20180415
List.add(Bean);
}
}
return List;
}