Java 集合和json数据之间互相转换

毕业设计中使用到了集合(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;
	}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值