JSON(spring+jackson)

(1)JsonUtil:create listToJson method
public static String listToJson(List list){
    try {
	    return objectMapper.writeValueAsString(list);
    } catch (JsonGenerationException e) {
	    e.printStackTrace();
    } catch (JsonMappingException e) {
	    e.printStackTrace();
    } catch (IOException e) {
	    e.printStackTrace();
    }
    return null;
}

(2)控制层调用原有接口,并封装Json数据返回,teacherToQQ方法如下
/**
 * @param url
 * @return Json:[{},{},{}]
 * @throws IOException 
 */
private String teacherToQQ(HttpServletRequest request, HttpServletResponse response){
    //1.validate param
    String uid= request.getParameter("uid");
    User user=loginService.getUserByUserId(uid);
    if(user==null || user.equals("")){
	    return "{\"result\":1,\"description\":\"教师ID不正确\"}";
    }
	//2.call service api,get return value
    List<QqDn> qqDns =    settingService.getTeacherQqDns(Long.parseLong(uid));
	//3.packages the data into json and return
    return JsonUtil.listToJson(qqDns);
}

(3)利用注解控制bean类属性排序和是否忽略
@JsonPropertyOrder({"relation","dn"})
public class QqDn {
    ...
    @JsonIgnore
    public int getNumber() {
        return number;
    }
    ...
}

你可能感兴趣的:(JSON(spring+jackson))