Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
415 views
in Technique[技术] by (71.8m points)

spring boot - Convert enum multiple values to Json in Java SpringBoot

Here I have a Rest Controller

 @RequestMapping(value = "/mobileNumber", method = RequestMethod.POST, produces = {
                MediaType.APPLICATION_JSON_VALUE })
        public ResponseEntity<ResponseBack> sentResponse() {
    
            return new ResponseEntity<ResponseBack>(ResponseBack.LOGIN_SUCCESS, HttpStatus.ACCEPTED);
    
        }

My Enum Class

public enum ResponseBack {
    LOGIN_SUCCESS(0, " success"), LOGIN_FAILURE(1, " failure");

    private long id;
    private final String message;

    // Enum constructor
    ResponseBack(long id, String message) {
        this.id = id;
        this.message = message;
    }

    public long getId() {
        return id;
    }

    public String getMessage() {
        return message;
    }
}

When I get the response back from the controller I am getting it as

"LOGIN_SUCCESS"

What I require is

{
    "id": "0",
    "message": "success"   
}

How can I deserialize it to Json and send response, is there any annotation for it. Please help, thanks.

question from:https://stackoverflow.com/questions/65859893/convert-enum-multiple-values-to-json-in-java-springboot

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You must use JsonFormat annotation

@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum ResponseBack {
...

So you tell that the Json representation of this enum will be the whole object. If you want a specific field to be returned (for example message field) you can annotate the method with JsonValue annotation

@JsonValue
public String getMessage() {
    return message;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...