2

How can I read JSON file and then put this into objects define in @Document - model for MongoDB. I'm looking for something like jackson object mapper in Java. It doesn't work here becouse Documen - model don't have empty constructor.

@Document(collection = "XXX")
 class Room(@Id
            private val id: String?,
            private val name: String){there is toString() method}


class Application{

@Bean
fun imageProcess(repo: MongoRepository) = CommandLineRunner {

    println("----------------Save customers!")


    for (room in read("C:/Users/Desktop/new.json")) {
        repo.save(room)
    }

}

val mapper = ObjectMapper().registerModule(KotlinModule())

fun read(path: String): Array<Room>? {

var temp: Array<Room>? = null
try {
    temp = mapper.readValue(File(path), Array<Room>::class.java)
} catch (ex: IOException) {
    ex.printStackTrace()
}

return temp

}

1
  • Could you provide the content of the JSON file and the error message? Commented Oct 18, 2018 at 20:33

1 Answer 1

2

Jackson should work together with this module: https://github.com/FasterXML/jackson-module-kotlin

"Previously a default constructor must have existed on the Kotlin object for Jackson to deserialize into the object. With this module, single constructor classes can be used automatically, and those with secondary constructors or static factories are also supported."

import com.fasterxml.jackson.module.kotlin.*

data class MyStateObject(val name: String, val age: Int)

...
val mapper = jacksonObjectMapper()

val state = mapper.readValue<MyStateObject>(json)
// or
val state: MyStateObject = mapper.readValue(json)
// or
myMemberWithType = mapper.readValue(json)
Sign up to request clarification or add additional context in comments.

2 Comments

@Document's syntax tells that variables must be as class parametres. And compiler don't let me create constructor. :( So how can I rewrite my model to could have deafault constructor?
if your JSON looks like {"id":"1", "name":"John"} you don't need a default constructor. Just add the module to your project and adapt the example to your class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.