service端:
BaseResponse对象描述返回格式,如:
{ "code": 1, "message": "成功查询到该用户信息", "data": { "name": "wuliao", "lover": "rose", "sex": 1, "email": "wuliao@gmail.com" }}
DatumResponse与DataResponse继承BaseResponse对象分别用来包装单个对象与对象list;
修改Model类增加新方法:
public DatumResponse getById(String id){ DatumResponse response = new DatumResponse(); M modelClass = null; if (StringUtil.isNotEmptyOrNull(id)) modelClass = findById(id); if (modelClass == null) { response.setCode(Code.FAIL).setMessage(getClass().getName()+" is not found"); } else { response.setDatum(modelClass); } return response; } public DataResponse getList(String sql, Object... paras){ DataResponse resp = new DataResponse(); Listresult = null; if (paras!=null) result = find(sql,paras); if (result == null || result.size() == 0) { resp.setMessage("未查询到数据"); } else { resp.setMessage("success"); resp.setData(result); } return resp; } public DatumResponse getFirst(String sql, Object... paras){ DatumResponse response = new DatumResponse(); M modelClass = null; if (paras!=null) modelClass = findFirst(sql, paras); if (modelClass == null) { response.setCode(Code.FAIL).setMessage(getClass().getName()+" is not found"); } else { response.setDatum(modelClass); } return response; }
在controller中返回封装对象即可,如:
/** * 根据id号查询单个用户 */ public void getEmp() { renderJson(Emp.dao.getUserById(getPara("userId"))); } /** * 查询某机构用户列表 */ public void getUserListOfOrg() { renderJson(Emp.dao.getUserListOfOrg(getPara("orgId"))); }
portal端:
主要是jackson的解析需要注意ObjectMapper的一些设置,如:
ObjectMapper objectMapper = Jackson.getJson().getObjectMapper(); objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES); objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); objectMapper.setSerializationInclusion(Include.NON_NULL); objectMapper.getDeserializationConfig().withoutFeatures(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(com.fasterxml.jackson.core.JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
另一点需要注意的是单对象的转换与list的对象转稍有差异:
单对象:
return objectMapper.readValue(jsonString, type);
对象list:
TypeFactory t = TypeFactory.defaultInstance();return objectMapper.readValue(jsonString,t.constructCollectionType(ArrayList.class,type));
备注:参考了空谷幽兰的设计,TKS