1
我想用Spring3.1的Jackson2.0.0,以便我可以使用jackson-Module-Hibernate。我已按照此處所述的步驟操作http://blog.pastelstudios.com/2012/03/12/spring-3-1-hibernate-4-jackson-module-hibernate/。所有這些似乎工作正常,但是當我嘗試使用JSON視圖,以便JSON只包含在視圖中的字段它不起作用。Jackson JSON Views忽略
活動視圖始終爲空。如何使視圖處於活動狀態?我已經嘗試了一天,沒有運氣......任何幫助都將不勝感激。提前致謝。
下面是相關的代碼。
這裏是映射器
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();
}
}
我的Spring配置
<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>
+1如何使用writerWithView和響應輸出流 – oak