读取json 文件中的内容并且实现分页工具类
当前的json内容必须是一个合法的json , 类似:
{
"colNames": "dfh,asd,asd,asd",
"data": [{
"gwew": "11",
"123": ".",
"435": ".",
"124": ".",
"12": ".",
"6666": "."
}, {
"6666.refGene": "CDC73",
"111": ".",
"421": ".",
"12": ".",
"4": ".",
"412": "."
}]
}
已经读取的json文件内容:jsonData
public class JsonNodePagingUtils {
public static JsonNode page(Integer currentPage, Integer pageSize, JsonNode jsonData) {
// 读取 JSON 文件
ObjectMapper mapper = new ObjectMapper();
// 读取json 文件的方法 当前方法没有使用
//JsonNode jsonData = mapper.readTree(new File("your_json_file.json"));
// 获取总数据量
int totalRecords = jsonData.get("data").size();
// 计算总页数
int totalPages = (int) Math.ceil((double) totalRecords / pageSize);
// 计算当前页数据的索引范围
int startIndex = (currentPage - 1) * pageSize;
int endIndex = Math.min(startIndex + pageSize, totalRecords);
// 获取当前页数据
List<JsonNode> currentPageData = new ArrayList<>();
Iterator<JsonNode> iterator = jsonData.get("data").elements();
int currentIndex = 0;
while (iterator.hasNext() && currentIndex < endIndex) {
JsonNode record = iterator.next();
if (currentIndex >= startIndex) {
currentPageData.add(record);
}
currentIndex++;
}
// 构造分页结果对象
return mapper.createObjectNode()
.put("currentPage", currentPage)
.put("pageSize", pageSize)
.put("totalPages", totalPages)
.put("totalRecords", totalRecords)
.set("data", mapper.valueToTree(currentPageData));
}
转换使用
// list 《jsonnode》 转jsonode
public static JsonNode convertListToJsonNode(List<JsonNode> nodeList) {
// 创建一个JsonNodeFactory实例
JsonNodeFactory factory = JsonNodeFactory.instance;
// 创建一个ArrayNode作为根节点
ArrayNode rootNode = factory.arrayNode();
// 将nodeList中的每个JsonNode添加到ArrayNode中
for (JsonNode node : nodeList) {
rootNode.add(node);
}
return rootNode;
}
/**
* jsonnode 转string
* @param node
* @return
* @throws Exception
*/
public static String convertJsonNodeToString(JsonNode node) throws Exception {
// 创建一个ObjectMapper实例
ObjectMapper objectMapper = new ObjectMapper();
// 将JsonNode对象转换为JSON字符串
return objectMapper.writeValueAsString(node);
}
public static JsonNode stringToJsonNode(String jsonString) {
ObjectMapper objectMapper = new ObjectMapper();
try {
return objectMapper.readTree(jsonString);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* jsonNode 转string
* @param jsonNode
* @return
*/
public static String convertToString(JsonNode jsonNode) {
ObjectMapper objectMapper = new ObjectMapper();
try {
return objectMapper.writeValueAsString(jsonNode);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}