【发布时间】:2015-05-05 21:57:51
【问题描述】:
spring 中是否有全局配置可以为所有使用@ResponseBody 注释的控制器禁用spring FAIL_ON_EMPTY_BEANS?
【问题讨论】:
spring 中是否有全局配置可以为所有使用@ResponseBody 注释的控制器禁用spring FAIL_ON_EMPTY_BEANS?
【问题讨论】:
如果您使用的是 Spring Boot,您可以在 application.properties 文件中设置以下属性。
spring.jackson.serialization.FAIL_ON_EMPTY_BEANS=false
感谢@DKroot 的宝贵意见。但我相信这应该是其他人自己的答案。
【讨论】:
你可以在配置configureMessageConverters的时候配置你的对象映射器
@Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
MappingJackson2HttpMessageConverter converter =
new MappingJackson2HttpMessageConverter(mapper);
return converter;
}
如果您想知道如何在您的应用程序中准确执行操作,请使用您的配置文件(xml 或 java 配置)更新您的问题。
这里有一个很好的article如何自定义消息转换器。
编辑:如果你使用 XML 而不是 Java 配置,你可以创建一个自定义的 MyJsonMapper 类扩展 ObjectMapper 自定义配置,然后使用它如下
public class MyJsonMapper extends ObjectMapper {
public MyJsonMapper() {
this.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
}
}
在您的 XML 中:
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper" ref="jacksonObjectMapper" />
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<bean id="jacksonObjectMapper" class="com.mycompany.example.MyJsonMapper" >
【讨论】:
spring.jackson.serialization.FAIL_ON_EMPTY_BEANS=false
在 spring boot 2.2.5 中找不到 spring.jackson.serialization.FAIL_ON_EMPTY_BEANS=false
我用这个
@Configuration
public class SerializationConfiguration {
@Bean
public ObjectMapper objectMapper() {
return new ObjectMapper().disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
}
}
【讨论】:
spring.jackson.serialization.FAIL_ON_EMPTY_BEANS=false 从来没有为我工作过,即使春天找到它
如果你使用的是 Spring Boot / JPA ,你还必须观察你是否在使用
findOne / enetiyManager.find(Clazz , id) 的 getOne (适用于 jpa getReference )
GetOne 依靠 ID 的持久性缓存引用,旨在检索其中只有 ID 的实体。它的用途主要是表示存在引用而不需要检索整个实体。
find 方法直接让持久化管理器获取持久化实例。
第二个会相应地观察你的注释@JsonIgnore,并会给你预期的结果。
// On entity...
@JsonIgnore
@OneToMany(fetch = FetchType.LAZY, mappedBy = "foo")
private List<Foo> fooCollection;
// later on persistence impl
entityManager.find(Caso.class, id);
// or on serivce
casoRepository.findById(id); //...
【讨论】:
对我来说,问题在于从 org.json.JSONObject 对象到 org.json.simple.JSONObject 的类型转换,我通过解析 的值来解决它>org.json.JSONObject 然后将其转换为 org.json.simple.JSONObject
JSONParser parser = new JSONParser();
org.json.simple.JSONObject xmlNodeObj = (org.json.simple.JSONObject) parser.parse(XMLRESPONSE.getJSONObject("xmlNode").toString());
【讨论】: