Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[QUESTION]枚举转换 #906

Closed
yancong303 opened this issue Nov 7, 2022 · 1 comment
Closed

[QUESTION]枚举转换 #906

yancong303 opened this issue Nov 7, 2022 · 1 comment
Labels
enhancement New feature or request question Further information is requested

Comments

@yancong303
Copy link

请描述您的问题

询问有关本项目的使用和其他方面的相关问题。
springboot项目下如果使用fastjson2。比如用户的性别,数据库是0,1,加入返回前端需要的是男和女,可以通过什么办法,在不改变原有bean的情况下,通过注解把性别 序列化。文档上没有找到枚举转换的示例。

@yancong303 yancong303 added the question Further information is requested label Nov 7, 2022
@wenshao wenshao added this to the 2.0.19 milestone Nov 8, 2022
@wenshao wenshao added the enhancement New feature or request label Nov 8, 2022
@wenshao
Copy link
Member

wenshao commented Nov 12, 2022

可以用ValueFilter,比如

import com.alibaba.fastjson2.filter.ValueFilter;

@Test
public void test() {
    Bean bean = new Bean();
    bean.type = Type.Big;

    ValueFilter valueFilter = (Object object, String name, Object value) -> {
        if (value instanceof Type) {
            switch ((Type) value) {
                case Big:
                    return "大";
                case Small:
                    return "小";
                default:
                    break;
            }
        }
        return value;
    };
    String json = JSON.toJSONString(bean, valueFilter);
    assertEquals("{\"type\":\"\"}", json);
}

public enum Type {
    Big(101),
    Small(102);

    public final int code;

    Type(int code) {
        this.code = code;
    }
}

public static class Bean {
    public Type type;
}

@wenshao wenshao closed this as completed Nov 12, 2022
@wenshao wenshao reopened this Nov 12, 2022
@wenshao wenshao removed this from the 2.0.19 milestone Nov 12, 2022
wenshao added a commit that referenced this issue Nov 12, 2022
@wenshao wenshao closed this as completed Nov 17, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request question Further information is requested
Projects
None yet
Development

No branches or pull requests

2 participants