| import com.alibaba.fastjson.JSONObject; |
| import java.util.List; |
| |
| |
| * @author obsidianlyg |
| */ |
| public class JsonPageUtil { |
| |
| public static Integer toInteger(JSONObject params, String key) { |
| return params.getInteger(key); |
| } |
| |
| public static String toString(JSONObject params, String key) { |
| String value = params.getString(key); |
| |
| if (value == null || value.isEmpty()) { |
| value = null; |
| } return value; |
| } |
| |
| public static boolean toBoolean(JSONObject params, String key) { |
| boolean value = false; |
| try { |
| value = params.getBoolean(key); |
| } catch (Exception e) { |
| return false; |
| } return value; |
| } |
| |
| public static JSONObject toPage(JSONObject params, List<JSONObject> list, int pageNumber, int pageSize) { |
| |
| JSONObject data = new JSONObject(); |
| data.put("pageSize", pageSize); |
| data.put("params", params); |
| |
| |
| |
| Integer count = list.size(); |
| data.put("total", count); |
| |
| |
| if (pageSize == -1) { |
| data.put("pageNumber", pageNumber); |
| data.put("rows", list); |
| return data; |
| } |
| |
| Integer pageCount; |
| if (count % pageSize == 0) { |
| pageCount = count / pageSize; |
| } else { |
| pageCount = count / pageSize + 1; |
| } |
| int fromIndex; |
| |
| int toIndex; |
| |
| pageNumber = Math.max(pageNumber - 1, 0); |
| |
| data.put("pageNumber", pageNumber + 1); |
| |
| if (!pageCount.equals(pageNumber+1)) { |
| fromIndex = pageNumber * pageSize; |
| toIndex = fromIndex + pageSize; |
| if(toIndex > count){ |
| fromIndex = (pageNumber-1) * pageSize; |
| toIndex = count; |
| } |
| } else { |
| fromIndex = pageNumber * pageSize; |
| toIndex = count; |
| } |
| |
| if (list.isEmpty()) { |
| data.put("rows", null); |
| return data; |
| } |
| |
| List<JSONObject> pageList = list.subList(fromIndex, toIndex); |
| data.put("rows", pageList); |
| return data; |
| } |
| } |