日期:2014-05-16  浏览次数:20309 次

collection与json格式的转换(mark帖)

做个记录。

?

?

今天前端要求组装一个如下的json格式数据,

{
					"sid"  :  "50012906",           
					"name" :  "低帮鞋",				
					"spell":  "dbx",                
					"leaf" :   2,             		         
				},
				{
					"sid"  :  "50012906",        
					"name" :  "低帮鞋",				
					"spell":  "dbx",                
					"leaf" :   2,             		
				},
				{
					"sid"  :  "50012906",           
					"name" :  "低帮鞋",				
					"spell":  "dbx",             
					"leaf" :   2,             		
				}
}
?

?


?

当然使用简单的方法生成。代码如下

?

?

?

 List<Map<String,String>> list = new ArrayList<Map<String, String>>();
       for(int i = 0; i < 5; i ++){
           Map<String,String> map = new TreeMap<String, String>();
           map.put("sid","50012906");
           map.put("name","zhenghui");
           map.put("isleaf","0");
           list.add(map);
       }
        net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject(list);
        System.out.println(jsonArray.toString());

?

?

另外记录一下单个Object转换的工具方法把

?

?

/**
     * 对象转jsonString
     * 
     * @param object
     * @return
     */
    public static String bean2json(Object object) {
        JSONObject jsonObject = JSONObject.fromObject(object);
        return jsonObject.toString();
    }

    /**
     * 根据对象生成的jsonString转换成该对象
     * 
     * @param json
     * @param beanClz
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T json2Object(String json, Class<T> clz) {
        return (T) JSONObject.toBean(JSONObject.fromObject(json), clz);
    }
?

?

?