카테고리 없음

작동하지 않는 Kotlin 개체에 JSON 문자열 만들기

기록만이살길 2021. 3. 1. 00:50
반응형

작동하지 않는 Kotlin 개체에 JSON 문자열 만들기

1. 질문(문제점):

Freelancer 개체와 서버에 저장해야하는 두 개의 이미지 파일이 포함 된 백엔드에 multipart / formdata 개체를 보내려고합니다. 디스크에 저장 부분은 작동하지만 JSON 문자열을 프리랜서 개체로 저장하는 것은 작동하지 않습니다. Jackson objectmapper로 문자열을 변환하려고 시도했지만 내가 잘못하고 있다고 생각합니다. 응용 프로그램을 디버깅하면 충돌이 발생 mapper.readValue하고 catch().

나는 또한을 (를) 사용하려고 kotlinx.serializer했지만 가져 오기가 작동하지 않아 Jackson으로 전환했습니다.

요청을받는 Kotlin 컨트롤러 :

   private val imageDirectory = System.getProperty("user.dir") + "/images/"
@PostMapping(consumes = ["multipart/form-data"])
fun saveUser(
        @RequestParam("profileImage") profileImage: MultipartFile,
        @RequestParam("fileIdImage") fileIdImage: MultipartFile,
        @RequestParam("freelancer") freelancer: String,
): ResponseEntity<*> {
    return try {
        val mapper = ObjectMapper();
        val freelancerJson: Freelancer = mapper.readValue(freelancer, Freelancer::class.java)
        println(freelancerJson.aboutYou)

        makeDirectoryIfNotExist(imageDirectory)
        val profileImagePath: Path = Paths.get(imageDirectory, profileImage.originalFilename)
        val idImagePath: Path = Paths.get(imageDirectory, fileIdImage.originalFilename)
        Files.write(profileImagePath, profileImage.bytes);
        Files.write(idImagePath, fileIdImage.bytes);
        JsonResponse(HttpStatus.OK, "Saved freelancer} ").createResponseEntity()
    } catch (e: Exception) {
        JsonResponse(HttpStatus.INTERNAL_SERVER_ERROR, e.message.toString()).createResponseEntity()
    }
}

vue를 사용하는 프런트 엔드의 요청 :

여기에 이미지 설명 입력

formdata의 콘솔 출력 :

여기에 이미지 설명 입력

프리랜서 모델 :

@Entity
data class Freelancer(
    @Id
    val id: Int,

    //maps ID to freelancer primary key
    @MapsId
    @OneToOne(targetEntity = User::class)
    @JoinColumn(name = "freelancer_id")
    //ignores the freelancer id because it is already mapped to val id
    @JsonIgnore
    val freelancerId: User,

    val firstName: String? = null,

    val lastName: String? = null,

    val dateOfBirth: Date? = null,
    val kvk: String? = null,
    val btw: String? = null,
    val phone: String? = null,
    val street: String? = null,
    val zipcode: String? = null,
    val city: String? = null,
    val housenumber: Int? = 0,
    val addition: String? = null,
    val nameCardHolder: String? = null,
    val iban: String? = null,
    val referral: String? = null,
    val specialism: String? = null,
    val aboutYou: String? = null,
    val motivation: String? = null,
    val workExperience: Int? = null,
    val driverLicense: Boolean? = null,
    val ownTransport: Boolean? = null,
    val identificationImage: String? = null,
    val smallBusinessScheme: Boolean? = false,
    val profileImage: String? = null,
    val previousWorkedPlatform: String? = null,
    val servicesAmount: Int? = null,
    val previousWorkedRating: Int? = null,
    val foundBy: String? = null,
    val privacyStatement: Boolean? = null,

    )

2. 해결방안:

내 모델이 다른 모델과 일대일 관계를 가지고 있기 때문에 Json을 모델에 매핑 할 때 포함해야했기 때문에 백엔드로 보내는 Json 개체에 ID를 추가하여 문제를 해결했습니다.

65751800
반응형