공부기록

공부기록, 2021-05-02(코틀린 jackson)

이재연 2021. 5. 2. 15:28

## 코틀린

compile "com.fasterxml.jackson.module:jackson-module-kotlin:2.9.+"

직렬화
val mapper = jacksonObjectMapper()

val articles = ArrayList<Article>() // Add elem to collection.

(1..3).forEach { n -> articles.add( Article(

"MyArticle $n",

System.currentTimeMillis(),

0,

"Hello,

Jackson! $n")) } // Convert Collection to JSON.

mapper .writerWithDefaultPrettyPrinter() .writeValue( File("./my_articles.json"), articles )

 

역직렬화

val mapper= jacksonObjectMapper()

val articles = mapper.readValue<ArrayList<Article>>(File("./my_articles.json"))

println(articles)

 

 

 

 

 

fun saveArticle(arr:List<Article>){
val mapper: ObjectMapper = jacksonObjectMapper()
var tempArticles = mutableListOf<Article>() // Add elem to collection.
for(i in arr){
tempArticles.add(i)
}
mapper.writerWithDefaultPrettyPrinter() .writeValue( File("C:\\Users\\이재연\\IdeaProjects\\Exam12\\src\\main\\json\\.my_articles.json"), articles )
}
fun readArticle() {
val mapper = jacksonObjectMapper()
val temp = mapper.readValue<ArrayList<Article>>(File("C:\\Users\\이재연\\IdeaProjects\\Exam12\\src\\main\\json\\.my_articles.json"))

for(i in temp){
articles.add(i)
}
}