Renan Scarela
Renan Scarela

Reputation: 357

Micronaut JSON serialization - use getters instead of fields

When using Spring MVC, by default, whenever your @RestControllers return an object, it will be serialized into a JSON based on its getters, instead of its fields.

Is there any way I can configure Micronaut to behave like this as well? Example:

public class User {

  private String email;
  private String password;

  public String getEmail() {
    return email;
  }

}

@Controller
public class UserController {

  public User getUser() {
    ...
  }

}

So this should return:

{
  "email": "email@addres.com"
}

instead of this:

{
  "email": "email@addres.com",
  "password": "pass"
}

I'm aware of Jackson's annotations, however, I'm just trying to understand if it's possible to configure Micronaut to behave like this.

Thanks.

Upvotes: 2

Views: 2219

Answers (1)

Dirk Deyne
Dirk Deyne

Reputation: 6936

It should work as expected, it should not be displaying the password. No fields are displayed if there is no getter (password).

Starting with a project without any features: micronaut launch

Then

import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.runtime.Micronaut;

public class Application {

    public static void main(String[] args) {
        Micronaut.run(Application.class, args);
    }
}

class User {
    String email;
    String password;

    public User(String email,String password) {
        this.email = email;
        this.password = password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getEmail() {
        return email;
    }
}

@Controller
class UserController {

    @Get
    public User getUser() {
        return new User("email@micronaut.io","secret");
    }

}

http://localhost:8080 results in:

{
"email": "email@address.com"
}

Upvotes: 2

Related Questions