잭슨은 낙타 사건을 지지하기 위해 밑줄을 긋다
인터넷에서 JSON 문자열을 가져옵니다.대부분의 JSON과 마찬가지로 긴 키는 밑줄로 구분되어 있습니다.기본적으로 JSON을 java-object로 역직렬화하는 것이 목표이지만, java-code에서는 밑줄을 사용하지 않습니다.
예를 들어, 제가 가지고 있는User
와 같은 반을 나누다.firstName
낙타 케이스의 필드, 동시에 나는 잭슨에게 지도를 만들라고 말해야 한다.first_name
JSON에서 키firstName
클래스 필드가능합니까?
class User{
protected String firstName;
protected String getFirstName(){return firstName;}
}
를 설정할 수 있습니다.ObjectMapper
카멜 대소문자를 밑줄이 있는 이름으로 변환하려면:
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
또는 다음 주석을 사용하여 특정 모델 클래스에 주석을 달 수 있습니다.
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
잭슨 2.7 이전에는 상수의 이름이 다음과 같이 지정되었습니다.
PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES
스프링 부트 어플리케이션인 경우 application.properties 파일에서
spring.context.naming-context=스네이크_케이스
또는 이 주석을 사용하여 모델 클래스에 주석을 붙입니다.
@Json Naming(프로퍼티 Naming Strategy).Scnake Case Strategy.class)
를 사용해야 합니다.@JsonProperty
기본 이름 매핑을 변경할 필드입니다.
class User{
@JsonProperty("first_name")
protected String firstName;
protected String getFirstName(){return firstName;}
}
자세한 내용은 API를 참조하십시오.
단일 클래스에 대해 이 기능을 사용하려면 다음과 같이 Property Naming Strategy를 @Json Naming과 함께 사용할 수 있습니다.
@JsonNaming(PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy.class)
public static class Request {
String businessName;
String businessLegalName;
}
시리얼화 대상:
{
"business_name" : "",
"business_legal_name" : ""
}
부터Jackson 2.7
그LowerCaseWithUnderscoresStrategy
에게 불리하게 비호감적으로SnakeCaseStrategy
다음 명령을 사용합니다.
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
public static class Request {
String businessName;
String businessLegalName;
}
위의 답변은 다음과 같습니다.@JsonProperty
그리고.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES
100% 정확합니다.다만, 코드 베이스의 설정을 가지는 Spring MVC 애플리케이션내에서 이것을 실행하려고 하는 사람도 있습니다.여기 샘플 코드가 있습니다(안에 있습니다).Beans.java
)를 사용하여 원하는 효과를 얻을 수 있습니다.
@Bean
public ObjectMapper jacksonObjectMapper() {
return new ObjectMapper().setPropertyNamingStrategy(
PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
}
현재의 베스트 프랙티스는 Jackson을 설정해 두는 것입니다.application.yml
(또는properties
) 파일입니다.
예:
spring:
jackson:
property-naming-strategy: SNAKE_CASE
보다 복잡한 구성 요건이 있는 경우 Jackson을 프로그래밍 방식으로 구성할 수도 있습니다.
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
@Configuration
public class JacksonConfiguration {
@Bean
public Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder() {
return new Jackson2ObjectMapperBuilder()
.propertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
// insert other configurations
}
}
아래 두 가지 버전의 잭슨 라이브러리에 대한 두 가지 전략을 모두 나타내는 답변은 거의 없습니다.
잭슨 2.6.*
ObjectMapper objMapper = new ObjectMapper(new JsonFactory()); // or YAMLFactory()
objMapper.setNamingStrategy(
PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
Jackson 2.7을 위해서.*
ObjectMapper objMapper = new ObjectMapper(new JsonFactory()); // or YAMLFactory()
objMapper.setNamingStrategy(
PropertyNamingStrategy.SNAKE_CASE);
모델 클래스에 주석을 달려면 다음을 사용합니다.
@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
대신:
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
2.12 이후 폐지되었습니다.
모든 모델 클래스에 주석을 다는 것은 과잉으로 보이며, Kenny의 답변은 나에게 효과가 없었습니다.https://stackoverflow.com/a/43271115/4437153.https://stackoverflow.com/a/43271115/4437153연재 결과는 여전히 낙타 사건이었다.
스프링 구성에 문제가 있다는 것을 깨달았기 때문에 다른 쪽에서 대응하지 않으면 안 되었습니다.누군가 유용하게 썼으면 좋겠는데, 만약 내가 스프링스 규칙에 어긋나는 일을 하고 있다면 알려주세요.
Spring MVC 5.2.5 및 Jackson 2.11.2용 솔루션
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setObjectMapper(objectMapper);
converters.add(converter);
}
}
클래스 필드의 @JsonProperty 주석을 사용하여 필드를 JSON의 정확한 이름에 매핑할 수 있습니다.
@JsonProperty("my_name") private String myName;
클래스에서 @JonNaming 주석을 사용할 수 있으며, 모든 필드는 snake 대소문자를 사용하여 역직렬화됩니다.
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class) public class MyClassWithSnakeStrategy { ...
}
ObjectMapper에서 setPropertyNamingStrategy 메서드를 사용하여 모든 시리얼라이제이션에 대해 구성할 수 있습니다.
= ObjectMapper ObjectMapper = object ObjectMapper()
set Property Naming Strategy(「Naming Strategy」).SNAK_CASE);
언급URL : https://stackoverflow.com/questions/10519265/jackson-overcoming-underscores-in-favor-of-camel-case
'source' 카테고리의 다른 글
Loader Manager에서의 initLoader와 restartLoader의 차이점 (0) | 2022.11.24 |
---|---|
mysql에서 현재 사용자 이름을 알 수 있는 방법이 있나요? (0) | 2022.11.24 |
v = (v == 0 ? 1 : 0 )로 표기하는 더 좋은 방법이 있습니까? (0) | 2022.11.15 |
Jese Vue: [Vue 경고]:구성 요소를 마운트하지 못했습니다. 템플릿 또는 렌더링 함수가 정의되지 않았습니다.얕은 마운트 또는 마운트에 빈 html이 반환됩니다. (0) | 2022.11.15 |
MySQL Count Distinent 값 여러 열의 동일한 행 (0) | 2022.11.15 |