Skip to content

Commit 147ad93

Browse files
author
pedro
committed
feat:解决Map的键无法从驼峰转为下划线的问题
1 parent 8be55d5 commit 147ad93

2 files changed

Lines changed: 36 additions & 3 deletions

File tree

src/main/java/io/github/talelin/merak/common/exception/RestExceptionHandler.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ public UnifyResponseVO processException(ConstraintViolationException exception,
7272
exception.getConstraintViolations().forEach(constraintViolation -> {
7373
String template = constraintViolation.getMessageTemplate();
7474
String path = constraintViolation.getPropertyPath().toString();
75-
msg.put(path, template);
75+
msg.put(StrUtil.toUnderlineCase(path), template);
7676
});
7777
UnifyResponseVO unifyResponse = new UnifyResponseVO();
7878
unifyResponse.setRequest(getSimpleRequest(request));
@@ -166,9 +166,9 @@ public UnifyResponseVO processException(MethodArgumentNotValidException exceptio
166166
errors.forEach(error -> {
167167
if (error instanceof FieldError) {
168168
FieldError fieldError = (FieldError) error;
169-
msg.put(fieldError.getField(), fieldError.getDefaultMessage());
169+
msg.put(StrUtil.toUnderlineCase(fieldError.getField()), fieldError.getDefaultMessage());
170170
} else {
171-
msg.put(error.getObjectName(), error.getDefaultMessage());
171+
msg.put(StrUtil.toUnderlineCase(error.getObjectName()), error.getDefaultMessage());
172172
}
173173
});
174174
UnifyResponseVO result = new UnifyResponseVO();

src/test/java/Jackson2Test.java

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import cn.hutool.core.util.StrUtil;
2+
import com.fasterxml.jackson.annotation.JsonFormat;
3+
import com.fasterxml.jackson.core.JsonProcessingException;
4+
import com.fasterxml.jackson.databind.ObjectMapper;
5+
import lombok.extern.slf4j.Slf4j;
6+
import org.junit.Test;
7+
8+
import java.util.HashMap;
9+
import java.util.Map;
10+
11+
@Slf4j
12+
public class Jackson2Test {
13+
14+
@Test
15+
public void testMap() throws JsonProcessingException {
16+
ObjectMapper mapper = new ObjectMapper();
17+
//mapper.setPropertyNamingStrategy(com.fasterxml.jackson.databind.PropertyNamingStrategy.SNAKE_CASE);
18+
//mapper.configOverride(Map.Entry.class).setFormat(JsonFormat.Value.forShape(JsonFormat.Shape.OBJECT));
19+
mapper.configOverride(Map.Entry.class).setFormat(JsonFormat.Value.forShape(JsonFormat.Shape.STRING));
20+
Map<String, Object> res = new HashMap<>();
21+
res.put("username", "pedro");
22+
res.put("userAge", 24);
23+
String s = mapper.writeValueAsString(res);
24+
log.info(s);
25+
}
26+
27+
@Test
28+
public void testCamel() throws JsonProcessingException {
29+
String str = "userAge";
30+
String s = StrUtil.toUnderlineCase(str);
31+
log.info(s);
32+
}
33+
}

0 commit comments

Comments
 (0)