对象与集合转为JSON

星期一上班状态不佳写个小功能需求将List集合对象转为JSON字符串传到页面上做下拉列表显示,可是当我把功能写完转换后还是一个对象还以为公共方法有问题但是排查后不是,后面将我的问题记录下来,防止自己下次再遇到此问题。前简单说一下有“HotActivityVo”对象里面有两个属性如下代码:

public class HotActivityVo {

	private Integer aId;// ID

	private String text;// 名称

	public Integer getaId() {
		return aId;
	}
	public void setaId(Integer aId) {
 		this.aId = aId;
	}
 	public String getText() {
		return text;
 	}
	public void setText(String text) {
		 this.text = text;
	}
}

  下面代码是将List集合对象转变为JSON字符串,如下代码

	public static String buildJsonArrayToStr(List<?> list) throws IOException{
		JSONArray jsonArray = new JSONArray();
		jsonArray.addAll(list);
		StringWriter out = new StringWriter();
		jsonArray.writeJSONString(out);
		return out.toString();
	}

 main方法测试一下,如下代码:

	public static void main(String[] args) {
		List<HotActivityVo> havl = new ArrayList<HotActivityVo>();
		HotActivityVo hav = new HotActivityVo();
		hav.setaId(1);
		hav.setText("苹果");
		HotActivityVo hav2 = new HotActivityVo();
		hav2.setaId(2);
		hav2.setText("西瓜");
		havl.add(hav);
		havl.add(hav2);
		try {
			String json = JsonUtils.buildJsonArrayToStr(havl);
			System.out.println(json);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

 运行后的结果:

[com.born.wom.action.vo.HotActivityVo@41408b80,com.born.wom.action.vo.HotActivityVo@7486a1f7]

 解决方法:

在"HotActivityVo"对象当中实现"JSONStreamAware"就可以解决问题,如下代码:

public class HotActivityVo implements JSONStreamAware {

	private Integer aId;// ID

	private String text;// 名称

	public Integer getaId() {
		return aId;
	}

	public void setaId(Integer aId) {
		this.aId = aId;
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}

	@Override
	public void writeJSONString(Writer write) throws IOException {
		LinkedHashMap<String, Object> jsonStr = new LinkedHashMap<String, Object>();
		jsonStr.put("configId", this.aId);
		jsonStr.put("content", this.text);
		JSONValue.writeJSONString(jsonStr, write);

	}

 运行结果:

[{"configId":1,"content":"苹果"},{"configId":2,"content":"西瓜"}]

猜你喜欢

转载自yeshuang.iteye.com/blog/2232493