Skip to content

Commit 91f1274

Browse files
committed
✨ 序列化enum的几种方式,支持返回json形式的枚举变量
1 parent b189c1e commit 91f1274

File tree

11 files changed

+335
-0
lines changed

11 files changed

+335
-0
lines changed

springboot-enums/.gitignore

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
HELP.md
2+
target/
3+
!.mvn/wrapper/maven-wrapper.jar
4+
!**/src/main/**
5+
!**/src/test/**
6+
7+
### STS ###
8+
.apt_generated
9+
.classpath
10+
.factorypath
11+
.project
12+
.settings
13+
.springBeans
14+
.sts4-cache
15+
16+
### IntelliJ IDEA ###
17+
.idea
18+
*.iws
19+
*.iml
20+
*.ipr
21+
22+
### NetBeans ###
23+
/nbproject/private/
24+
/nbbuild/
25+
/dist/
26+
/nbdist/
27+
/.nb-gradle/
28+
build/
29+
30+
### VS Code ###
31+
.vscode/

springboot-enums/pom.xml

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
3+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4+
<modelVersion>4.0.0</modelVersion>
5+
<artifactId>springboot-enums</artifactId>
6+
<version>0.0.1-SNAPSHOT</version>
7+
<name>springboot-enums</name>
8+
<description>rest接口获取枚举类属性的示例</description>
9+
10+
<parent>
11+
<groupId>me.zhyd.springboot</groupId>
12+
<artifactId>springboot-learning</artifactId>
13+
<version>0.0.1-SNAPSHOT</version>
14+
</parent>
15+
16+
<dependencies>
17+
18+
</dependencies>
19+
20+
</project>
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package me.zhyd.springboot.enums;
2+
3+
import me.zhyd.springboot.enums.enums.GenderEnum;
4+
import me.zhyd.springboot.enums.enums.StatusEnum;
5+
import me.zhyd.springboot.enums.enums.TypeEnum;
6+
import me.zhyd.springboot.enums.model.User;
7+
import org.springframework.http.MediaType;
8+
import org.springframework.web.bind.annotation.*;
9+
10+
import java.util.ArrayList;
11+
import java.util.List;
12+
13+
/**
14+
* @author yadong.zhang (yadong.zhang0415(a)gmail.com)
15+
* @version 1.0
16+
* @website https://www.zhyd.me
17+
* @date 2019/7/3 9:49
18+
* @since 1.8
19+
*/
20+
@RestController
21+
public class RestApiController {
22+
23+
@RequestMapping("/users")
24+
public Object users() {
25+
List<User> userList = new ArrayList<>();
26+
User user = null;
27+
for (int i = 0; i < 2; i++) {
28+
user = new User();
29+
user.setGender(i % 2 == 0 ? GenderEnum.MALE : GenderEnum.FAMALE);
30+
user.setType(i % 2 == 0 ? TypeEnum.ADMIN : TypeEnum.USER);
31+
user.setStatus(i % 2 == 0 ? StatusEnum.INUSE : StatusEnum.DISABLED);
32+
user.setUsername("user_" + i);
33+
user.setSite("https://www.zhyd.me");
34+
user.setGit(new String[]{"https://gitee.com/yadong.zhang", "https://github.com/zhangyd-c"});
35+
userList.add(user);
36+
}
37+
return userList;
38+
}
39+
// @RequestMapping(value = "/saveUser", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
40+
@RequestMapping(value = "/saveUser")
41+
public Object saveUser(User user) {
42+
return user;
43+
}
44+
45+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package me.zhyd.springboot.enums;
2+
3+
import org.springframework.boot.SpringApplication;
4+
import org.springframework.boot.autoconfigure.SpringBootApplication;
5+
6+
@SpringBootApplication
7+
public class SpringbootEnumsApplication {
8+
9+
public static void main(String[] args) {
10+
SpringApplication.run(SpringbootEnumsApplication.class, args);
11+
}
12+
13+
}
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
package me.zhyd.springboot.enums.config;
2+
3+
import com.alibaba.fastjson.JSONObject;
4+
import com.alibaba.fastjson.serializer.SerializerFeature;
5+
import com.alibaba.fastjson.serializer.ValueFilter;
6+
import com.alibaba.fastjson.support.config.FastJsonConfig;
7+
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
8+
import org.springframework.beans.factory.annotation.Value;
9+
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
10+
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
11+
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
12+
import org.springframework.context.annotation.Bean;
13+
import org.springframework.context.annotation.Configuration;
14+
import org.springframework.http.MediaType;
15+
import org.springframework.http.converter.HttpMessageConverter;
16+
import org.springframework.util.StringUtils;
17+
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
18+
19+
import java.util.ArrayList;
20+
import java.util.List;
21+
import java.util.Map;
22+
23+
@Configuration
24+
public class WebMvcConf implements WebMvcConfigurer {
25+
26+
@Override
27+
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
28+
converters.forEach(System.out::println);
29+
}
30+
31+
private boolean isJson(String str) {
32+
return !StringUtils.isEmpty(str) && (str.charAt(0) == '{' && str.charAt(str.length() - 1) == '}');
33+
}
34+
35+
/**
36+
* 自定义FastJsonHttpMessageConverter处理api中的枚举
37+
* 参考资料:
38+
* https://blog.csdn.net/mickjoust/article/details/51671060
39+
* https://ask.csdn.net/questions/358742?sort=id
40+
* https://www.cnblogs.com/china-baizhuangli/p/8630787.html
41+
* https://blog.csdn.net/u010246789/article/details/52539576
42+
* https://blog.csdn.net/yiifaa/article/details/73610334
43+
*/
44+
45+
/*@Configuration
46+
@ConditionalOnClass({FastJsonHttpMessageConverter.class})
47+
@ConditionalOnProperty(
48+
name = {"spring.http.converters.preferred-json-mapper"},
49+
havingValue = "fastjson",
50+
matchIfMissing = true
51+
)
52+
public class FastJsonHttpMessageConvertersConfiguration {
53+
54+
@Bean
55+
@ConditionalOnMissingBean({FastJsonHttpMessageConverter.class})
56+
public FastJsonHttpMessageConverter fastJsonHttpMessageConverter() {
57+
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
58+
59+
FastJsonConfig fastJsonConfig = new FastJsonConfig();
60+
// https://blog.csdn.net/u010246789/article/details/52539576
61+
fastJsonConfig.setSerializerFeatures(
62+
SerializerFeature.PrettyFormat,
63+
SerializerFeature.WriteEnumUsingToString
64+
);
65+
// 中文乱码解决方案 https://www.cnblogs.com/china-baizhuangli/p/8630787.html
66+
List<MediaType> mediaTypes = new ArrayList<>();
67+
mediaTypes.add(MediaType.APPLICATION_JSON_UTF8);//设定json格式且编码为UTF-8
68+
converter.setSupportedMediaTypes(mediaTypes);
69+
70+
ValueFilter valueFilter = (o, s, o1) -> {
71+
if (o1 instanceof Enum) {
72+
// 枚举类的序列化结果转成map
73+
String str = String.valueOf(o1);
74+
if (isJson(str)) {
75+
o1 = JSONObject.parseObject(String.valueOf(o1), Map.class);
76+
}
77+
}
78+
return o1;
79+
};
80+
fastJsonConfig.setSerializeFilters(valueFilter);
81+
82+
converter.setFastJsonConfig(fastJsonConfig);
83+
84+
return converter;
85+
}
86+
87+
}*/
88+
89+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package me.zhyd.springboot.enums.enums;
2+
3+
import com.fasterxml.jackson.annotation.JsonFormat;
4+
5+
/**
6+
* @author yadong.zhang (yadong.zhang0415(a)gmail.com)
7+
* @version 1.0
8+
* @website https://www.zhyd.me
9+
* @date 2019/7/3 9:46
10+
* @since 1.8
11+
*/
12+
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
13+
public enum GenderEnum {
14+
MALE("男"),
15+
FAMALE("女");
16+
private String desc;
17+
18+
GenderEnum(String desc) {
19+
this.desc = desc;
20+
}
21+
22+
public String getDesc() {
23+
return desc;
24+
}
25+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package me.zhyd.springboot.enums.enums;
2+
3+
import com.alibaba.fastjson.annotation.JSONType;
4+
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
5+
6+
/**
7+
* @author yadong.zhang (yadong.zhang0415(a)gmail.com)
8+
* @version 1.0
9+
* @website https://www.zhyd.me
10+
* @date 2019/7/3 9:47
11+
* @since 1.8
12+
*/
13+
@JSONType(serializeEnumAsJavaBean = true)
14+
public enum StatusEnum {
15+
INUSE("使用中"),
16+
UNUSED("未使用"),
17+
DISABLED("已禁用");
18+
19+
private String desc;
20+
21+
StatusEnum(String desc) {
22+
this.desc = desc;
23+
}
24+
25+
public String getDesc() {
26+
return desc;
27+
}
28+
29+
public String getName() {
30+
return this.name();
31+
}
32+
}
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package me.zhyd.springboot.enums.enums;
2+
3+
import com.alibaba.fastjson.JSONObject;
4+
5+
import java.util.HashMap;
6+
import java.util.Map;
7+
8+
/**
9+
* @author yadong.zhang (yadong.zhang0415(a)gmail.com)
10+
* @version 1.0
11+
* @website https://www.zhyd.me
12+
* @date 2019/7/3 9:47
13+
* @since 1.8
14+
*/
15+
public enum TypeEnum {
16+
ADMIN("管理员"),
17+
USER("普通用户");
18+
private String desc;
19+
20+
TypeEnum(String desc) {
21+
this.desc = desc;
22+
}
23+
24+
public String getDesc() {
25+
return desc;
26+
}
27+
28+
@Override
29+
public String toString() {
30+
Map<String, Object> map = new HashMap<>();
31+
map.put("name", this.name());
32+
map.put("desc", this.getDesc());
33+
return JSONObject.toJSONString(map);
34+
}
35+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package me.zhyd.springboot.enums.model;
2+
3+
import lombok.Data;
4+
import me.zhyd.springboot.enums.enums.GenderEnum;
5+
import me.zhyd.springboot.enums.enums.StatusEnum;
6+
import me.zhyd.springboot.enums.enums.TypeEnum;
7+
8+
import java.io.Serializable;
9+
10+
/**
11+
* @author yadong.zhang (yadong.zhang0415(a)gmail.com)
12+
* @version 1.0
13+
* @website https://www.zhyd.me
14+
* @date 2019/7/3 9:44
15+
* @since 1.8
16+
*/
17+
@Data
18+
public class User implements Serializable {
19+
private String username;
20+
private String site;
21+
private String[] git;
22+
private GenderEnum gender;
23+
private TypeEnum type;
24+
private StatusEnum status;
25+
26+
public String getTypeEnumDesc() {
27+
return null == type ? null : type.getDesc();
28+
}
29+
}

springboot-enums/src/main/resources/application.properties

Whitespace-only changes.

0 commit comments

Comments
 (0)