0

Sup guys. Learning Scala with Spring. Have searched a lot and couldn't find anything that really helped. I developed on Node.js before and I'm confused a bit now.

I do not understand how I should send JSON in Response. I want something like that (at least I'd do similar on js):

@RestController
@RequestMapping(path = Array("/api"))
class Auth {
  @GetMapping(path = Array("/users"))
  def getString(@RequestParam(value = "id") id: String): User = {
    val user: User = Users.searchUser(id)
    user
  }
}

So the problem is: I can't send JSON. I need to serialize it, as I understand, because Scala can't do such a thing by itself. I found next next type for Response : MediaType.APPLICATION_JSON_VALUE, e.g.

@PostMapping(path = Array("/users"), produces = Array(MediaType.APPLICATION_JSON_VALUE))

And for testing I overrided toString function of class, that contains information about users, so it builds json-similar string. It works, but it is not the solution, it's awful. Also I have an error if I try using MediaType.APPLICATION_JSON (Type mismatch: expected %any_scala_type%, actual: MediaType).

How should I create JSON / serialize objects into JSON to send it to client?

Nikita
  • 101
  • 7
  • You probably forgot to add Jackson or Gson to your dependencies. That's what serializes ojects to JSON. Not Scala. What do you get when requesting `/users?id=someUserId`? – JB Nizet Oct 27 '18 at 21:39
  • Plese check the [answer here on how to encode scala case classes as JSON](https://stackoverflow.com/a/52581955/432903), which is what you looking for. Also [Scala, @ResponseBody](https://stackoverflow.com/a/19488460/432903) – prayagupa Oct 27 '18 at 21:46

0 Answers0