You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java字符串替换报错:Cannot invoke CharSequence.toString(),replacement为null

问题分析与解决方案

这个错误的核心原因是Java的String.replace(CharSequence, CharSequence)方法不允许第二个参数(替换值)为null,当你传入null时就会触发Cannot invoke "java.lang.CharSequence.toString()" because "replacement" is null异常。结合你的代码,可能的null来源及解决方法如下:

可能的Null来源

  1. Session获取的参数:原Scala代码中session("xxx").as[String]在key不存在时会直接抛出异常,不会返回null;但Java的session.getString("xxx")在key不存在时会返回null,这些null值传入replace方法就会触发错误。
  2. Student列表拼接逻辑:如果studentsList是空字符串,循环拼接后builder末尾的逗号处理可能引发问题(不过这种情况会先抛StringIndexOutOfBoundsException,不是当前报错的直接原因)。
  3. 其他变量:title、availableDate、dueDate如果为null,同样会导致replace报错。

修正后的代码

String[] studentsArr = studentsList.split(",");
StringBuilder builder = new StringBuilder();

// 过滤空的studentId,避免无效条目
for (String i : studentsArr) {
    if (i != null && !i.trim().isEmpty()) {
        builder.append("{\"studentPersonalRefId\":\"").append(i).append("\"},");
    }
}

// 处理空builder的情况,避免substring索引越界
String studentRefs = "";
if (builder.length() > 0) {
    studentRefs = builder.substring(0, builder.length() - 1);
}

// 给session参数设置默认值,避免null
String teacherRefId = Optional.ofNullable(session.getString("userRefId")).orElse("");
String sectionId = Optional.ofNullable(session.getString("sectionRefId")).orElse("");
String assignmentType = Optional.ofNullable(session.getString("assignmentType")).orElse("");

// 确保其他变量不为null
title = Optional.ofNullable(title).orElse("");
availableDate = Optional.ofNullable(availableDate).orElse("");
dueDate = Optional.ofNullable(dueDate).orElse("");

// 执行替换
String body = parsedString.replace("\"$studentRefIdList\"", studentRefs)
        .replace("$title", title)
        .replace("$teacherRefId", teacherRefId)
        .replace("$sectionId", sectionId)
        .replace("$sif_RefObject", assignmentType)
        .replace("$availableDate", availableDate)
        .replace("$dueDate", dueDate);

return body;

额外优化建议

手动拼接JSON容易出错且难以维护,建议使用Jackson或Gson等JSON库构建请求体,示例如下(Jackson):

ObjectMapper mapper = new ObjectMapper();
Map<String, Object> requestBody = new HashMap<>();

// 填充基础字段
requestBody.put("title", Optional.ofNullable(title).orElse(""));
requestBody.put("teacherRefId", Optional.ofNullable(session.getString("userRefId")).orElse(""));
requestBody.put("sectionId", Optional.ofNullable(session.getString("sectionRefId")).orElse(""));
requestBody.put("sif_RefObject", Optional.ofNullable(session.getString("assignmentType")).orElse(""));
requestBody.put("availableDate", Optional.ofNullable(availableDate).orElse(""));
requestBody.put("dueDate", Optional.ofNullable(dueDate).orElse(""));

// 构建student列表
List<Map<String, String>> studentList = new ArrayList<>();
for (String id : studentsArr) {
    if (id != null && !id.trim().isEmpty()) {
        Map<String, String> student = new HashMap<>();
        student.put("studentPersonalRefId", id);
        studentList.add(student);
    }
}
requestBody.put("studentRefIdList", studentList);

// 转换为JSON字符串
String body = mapper.writeValueAsString(requestBody);

内容的提问来源于stack exchange,提问作者Alexb1999

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 03:24:24