Solr nextCursorMark解析错误及编码处理求助
解决cursorMark解析错误的问题
我之前在实现类似的分页搜索功能时,也踩过几乎一模一样的坑!你的问题核心出在对返回的nextCursorMark进行JSON解析时的处理方式错误,下面来一步步分析和解决:
为什么会报错?
1. 使用toString()的问题
当你调用jsonObject.get("nextCursorMark").toString()时,返回的是带双引号的JSON字符串表示。比如服务端实际返回的nextCursorMark值是:
AoE/SkhJVkVfRFNDNjAwNDlfVklTVEFfVklTVEFQX1RaX0RCOi8vSGl2ZSBNZXRhc3RvcmUvZHNjNjAwNDlfdmlzdGFfdmlzdGFwX3R6X2RiL2Fucl9sb2dvbl9sb2cvbG9nX3RpbWVzdGFtcA==
但toString()会返回:
"AoE/SkhJVkVfRFNDNjAwNDlfVklTVEFfVklTVEFQX1RaX0RCOi8vSGl2ZSBNZXRhc3RvcmUvZHNjNjAwNDlfdmlzdGFfdmlzdGFwX3R6X2RiL2Fucl9sb2dvbl9sb2cvbG9nX3RpbWVzdGFtcA=="
服务端收到带双引号的cursorMark后,会判定为无效格式,自然抛出"Unable to parse 'cursorMark'"的错误。
2. 使用getAsString()出现数组越界
这个问题大概率是因为你没有先校验nextCursorMark对应的JSON元素类型。如果服务端在某些边界场景下(比如最后一页)返回的nextCursorMark不是字符串类型(比如null或者意外的JSON数组),直接调用getAsString()就会触发类型转换错误,导致数组越界或者ClassCastException。
正确的处理方式
你需要先校验JSON元素的类型,确保它是字符串类型后再获取值,同时修正循环里的moreResultsExists逻辑,避免空指针或无效循环。修改后的代码如下:
do { String response = RestClient.doGet(url, userName, password, offSetTemp, pageSize, cursorMark); System.out.println("res:----"+response); jsonObject = ProfileDataExportUtil.getJson(response); JsonArray profilingInfo = null; if (jsonObject.has("items")) { profilingInfo = jsonObject.get("items").getAsJsonArray(); } // 修正:如果没有数据,直接标记没有更多结果并跳过 if (profilingInfo == null || profilingInfo.size() == 0) { moreResultsExists = false; continue; } moreResultsExists = true; ProfileDataExporter.writeProfileInformation(bWriter, profilingInfo); if (!jsonObject.has("nextCursorMark")) { moreResultsExists = false; continue; } // 核心:先校验类型再获取字符串值 JsonElement cursorElement = jsonObject.get("nextCursorMark"); if (cursorElement.isJsonPrimitive() && cursorElement.getAsJsonPrimitive().isString()) { cursorMark = cursorElement.getAsString(); } else { // 遇到非字符串类型的cursorMark,停止循环 moreResultsExists = false; } } while (moreResultsExists);
额外注意点
如果修改后仍然报错,可以检查返回的nextCursorMark是否包含URL敏感字符(比如/、=),这种情况下需要对cursorMark做URL编码:
cursorMark = URLEncoder.encode(cursorElement.getAsString(), "UTF-8");
不过一般服务端返回的cursorMark会是Base64编码后的URL安全字符串,所以这个步骤可能不是必须的,但可以作为排查方向。
内容的提问来源于stack exchange,提问作者Ashwin Venkatesh
相关产品推荐
相关产品推荐

