我正在尝试将 Jackson2.0.0 与 Spring3.1 一起使用,以便可以使用 jackson-Module-Hibernate。我已经按照这里描述的步骤http://blog.pastelstudios.com/2012/03/12/spring-3-1-hibernate-4-jackson-module-hibernate/。所有这一切似乎都很好,但是当我尝试使用 JSON 视图以便 JSON 仅包含视图中的字段时,它不起作用。
活动视图始终为空。如何使视图处于活动状态?我已经尝试了一天没有运气......任何帮助都将不胜感激。提前致谢。
以下是相关代码。
这是映射器
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.hibernate4.Hibernate4Module;
public class HibernateAwareObjectMapper extends ObjectMapper {
public HibernateAwareObjectMapper() {
Hibernate4Module hm = new Hibernate4Module();
registerModule(hm);
hm.configure(Hibernate4Module.Feature.FORCE_LAZY_LOADING, true);
}
}
这是视图类
public class DiffViews {
public static class Public { }
}
这是我使用视图的 POJO
@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@id")
@JsonIgnoreProperties(ignoreUnknown=true)
@Entity
public class Premium implements java.io.Serializable {
@JsonView(DiffViews.Public.class)
private String sequence;
@JsonView(DiffViews.Public.class)
@Column(name = "SEQUENCE", nullable = false, length = 4)
public String getSequence() {
return this.sequence;
}
public void setSequence(String sequence) {
this.sequence = sequence;
}
@Column(name = "NAME", nullable = false)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
)
在我的弹簧控制器中
@RequestMapping("/cartonPremium")
public void listAll(
@RequestParam("page") int page, @RequestParam("rows") int maxResults,
@RequestParam("sidx") String sortKey, @RequestParam("sord") String sortOrder, HttpServletResponse response) {
HibernateAwareObjectMapper mapper = new HibernateAwareObjectMapper();
mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.enable(SerializationFeature.WRITE_CHAR_ARRAYS_AS_JSON_ARRAYS);
mapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION );
JqgridResponse<Premium> gridResponse = new JqgridResponse<Premium>();
gridResponse.setRows(premiumList);
gridResponse.setRecords(""+premiumList.size());
gridResponse.setTotal(""+premiumList.size());
gridResponse.setPage(""+page);
try {
ObjectWriter objWriter= mapper.writerWithView(DiffViews.Public.class);
Class<?> xxx = mapper.getSerializationConfig().getActiveView();
objWriter.writeValue(response.getOutputStream(), gridResponse);
//mapper.writerWithView(DiffViews.Public.class).writeValue(response.getOutputStream(), gridResponse);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
我的弹簧配置
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="com.creata.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="com.creata.json.HibernateAwareObjectMapper" />
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>