简体   繁体   中英

How to convert normal class to and from JSON with Scala?

I found some examples for case class conversion with JSON. But what about normal classes?

Suppose I have a normal class:

class User {
  var username = "Freewind"
  var email = "test@test.com"
  var age = 10
}

How to convert it to JSON, as the following?

{
    "username" : "Freewind",
    "email" : "test@test.com",
    "age" : 10
}

And how to convert it back to a User object?


Update:

I removed "lift-json" from the question. Any library will be fine.

I would strongly advise switching to case classes as it opens up more doors as far as frameworks are concerned. If you don't want to switch though, one option that will work is Jackson via the Jackson Scala Module . Using that library and the following code, I was able to get proper two way serialization of your User class:

  val mapper = new ObjectMapper()
  mapper.registerModule(DefaultScalaModule)

  val sw = new StringWriter
  val u = new User
  mapper.writeValue(sw, u)
  val json = sw.toString()
  val user = mapper.readValue(json.getBytes, classOf[User])

It's a little less scala friendly then the other frameworks that depend on case classes, but it will get the job done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM