java - Kotlin map 函数在第一次迭代时更改所有子对象
问题描述
我有一个问题,我试图迭代一个对象数组并将所有图像更改为 base64,包括子对象。当我这样做时,对象(作业)会像预期的映射函数一样被一一更改,但是当我想要更改每个迭代子对象时,它会做一些奇怪的事情。在第一次迭代中,第一个对象 (Job) 正确转换了图像,但是当地图尝试更改子对象 (Company) 时,它会更改所有其他父对象 (Job) 引用图像的子对象 (Company) ,所以当第二次迭代开始时,对图像的引用消失了,应用程序崩溃了(但只有所有的子引用(公司)在第一次迭代时被改变)。
视觉表现:
开始第一次迭代: http: //prntscr.com/18ijsnq
第一次迭代结束:http: //prntscr.com/18ik1cy
第二次迭代开始:http: //prntscr.com/18ik97w
正如您所看到的,公司子对象已针对数组中的所有 Job 对象进行了更改,但我希望它在每次迭代时都会一个一个地更改。
这是我的数据模型:
带地图的代码:
@GetMapping
fun getAllJobs(): ResponseEntity<*> {
return try {
val jobList: List<Job> = jobRepository.findAll()
jobList.map {
val file = FileUtils.readFileToByteArray(File("images/job/" + it.jobImage))
val companyFile = FileUtils.readFileToByteArray(File("images/company/" + it.company.logo))
it.company.logo = "data:image/jpeg;base64," + Base64.getEncoder().encodeToString(companyFile)
it.jobImage = "data:image/jpeg;base64," + Base64.getEncoder().encodeToString(file)
}
JsonDataResponse(HttpStatus.OK, "Retrieved lists of jobs ", jobList).createResponseEntity()
} catch (e: Exception) {
JsonResponse(HttpStatus.INTERNAL_SERVER_ERROR, e.stackTraceToString()).createResponseEntity()
}
}
我对 mapIndexed 的尝试:
@GetMapping
fun getAllJobs(): ResponseEntity<*> {
return try {
val jobList: List<Job> = jobRepository.findAll()
jobList.mapIndexed { i: Int, job: Job ->
val file = FileUtils.readFileToByteArray(File("images/job/" + job.jobImage))
val companyFile = FileUtils.readFileToByteArray(File("images/company/" + jobList[i].company.logo))
jobList[i].company.logo = "data:image/jpeg;base64," + Base64.getEncoder().encodeToString(companyFile)
job.jobImage = "data:image/jpeg;base64," + Base64.getEncoder().encodeToString(file)
}
JsonDataResponse(HttpStatus.OK, "Retrieved lists of jobs ", jobList).createResponseEntity()
} catch (e: Exception) {
JsonResponse(HttpStatus.INTERNAL_SERVER_ERROR, e.stackTraceToString()).createResponseEntity()
}
}
堆栈跟踪:
> java.io.FileNotFoundException: File 'images\company\data:image\jpeg;base64,\9j\4AAQSkZJRgABAQAAAQABAAD...AAAAAAH\Z' does not exist
at org.apache.commons.io.FileUtils.openInputStream(FileUtils.java:297) ~[commons-io-2.6.jar:2.6]
at org.apache.commons.io.FileUtils.readFileToByteArray(FileUtils.java:1851) ~[commons-io-2.6.jar:2.6]
at com.example.bouwershub.controllers.JobController.getAllJobs(JobController.kt:32) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at....
为什么会这样?
解决方案
推荐阅读
- linux - 文件未在存储和公用文件夹之间同步
- java - 使用名为 Wait 的变量声明特征会导致覆盖编译器错误
- html - 在浏览器中测试 Quill 生成的 HTML
- html - 使用 href 在 HTML 中传递参数
- python - 如何在python中使用csv文件中的边框构建表格
- javascript - 将语言环境日期转换为日期对象
- angular - 如何使用 navigationExtras 动态发送数据数组?
- reactjs - 非反应函数中的 Redux
- javascript - 使用 JS 替换 DOM 中的 html
- powershell - 计算文本字符串的实例并输出到文本文件