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

java 构造json对象
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;
.
.
.
if (CollectionUtil.isNotEmpty(userModelList)) {
List<JSONObject> list = new ArrayList<JSONObject>();
Map o = new HashMap();
for (UserModel userModel : userModelList) {
Map map =new HashMap();     
map.put("id",userModel.getUser_id_site());
map.put("name",userModel.getUser_nike_name());
map.put("image",userModel.getUser_image_big());

JSONObject jsonobj = JSONObject.fromObject(map);
list.add(jsonobj);
}
Map oo = new HashMap();
oo.put("users",list.toArray());

Map status = new HashMap();
oo.put("status","ok");

JSONObject jsonobj = JSONObject.fromObject(oo);
jsonobj.putAll(status);
o.put("jsonp", jsonobj);
System.out.println(o.toString());
return o.toString();
}


//////////结果类似这样:

{jsonp={"users":[{"id":"1","name":"客服NO1","image":null},{"id":"asfdafasd","name":"sdaf","image":"sadfas"},{"id":"asfdafasd","name":"sdaf","image":"sadfas"}],"status":"ok"}}

你也可以继续嵌套构造多级