java - SpringMVC中使用jackson返回json时如何将枚举转为json
怪我咯
怪我咯 2017-04-18 10:01:21
0
3
821

SpringMVC中使用jackson返回json时如何将枚举转为json

在网上搜过,给出的方案是在要转换的枚举的get方法上加上@JsonValue注解,我加上后报了错
下面是我错误的示例:
StatusEnum:

IndexController:

POM.xml中jackson与Spring的版本号:

报的错:

怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(3)
PHPzhong

My approach is to write a public method to convert to Map
Implement it however convenient it is. In fact, I think the annotation should be placed on the get method of the enumeration instance

public class Result {
    private StatusEnum status;
    ...
    
    @JsonValue
    public StatusEnum getStatus() {
        return status;
    }
    
    public void setStatus(status) {
        this.status = status;
    }
}

I haven’t used this before, so I don’t know much about it, but you can try it.
I couldn’t resist my curiosity and tried it. . . The one above is not feasible. . . But don’t use @JsonValue

@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum StatusEnum {
    STATUS_ERROR("200", "OK"),
    STATUS_SUCCESS(404, "Not Found");
    
    private Stringcode;
    private String msg;
    
    private Status(String code, String msg) {...}

    //getter & setter
    ...
}

Personal test, it works

Ty80

enum默认jackson只能序列化为索引和枚举名称,如果你需要返回{} json object 需要自已实现Serializer
Jdk8Module 参考这个实现自己对StatusEnumDo the processing.

PHPzhong

Reference: http://blog.csdn.net/sdyy321/...

You can take a look at the following points:

  1. SerializationFeature.WRITE_ENUMS_USING_TO_STRING

  2. @JsonSerialize@JsonDeserialize

  3. @JsonCreator

If you just need serialization, you can use 1 and @JsonSerialize to implement it simply. The former is simple and the latter is flexible;
If you need deserialization, you can use @JsonDeserialize code> and @JsonSerialize实现,前者简单,后者灵活;
如果需要反序列化,那可以用@JsonDeserialize@JsonCreator, the former is flexible and the latter is simple :)

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template