假設我有一個如下對象的列表:LinkedList<JsonAssessment> jsonAssessments...
。將Spring MVC中返回給ResponseBody的JSON對象重命名爲
它返回到這種方法:
@RequestMapping(value = "mapping", method = RequestMethod.POST)
public
@ResponseBody
List<JsonAssessment> doSomething(....) {
.....
}
我提出AJAX調用該控制器一切都如預期的那樣正常工作,但我不喜歡返回命名我的JSON。在螢火蟲我看到:
{"LinkedList":[{"assessmentName":"........
是我如何可以重命名根元素LinkedList
這個問題?有我需要設置的配置嗎?
編輯
我不希望使用任何包裝對象。
編輯
我ObjectMapper:
public class JsonObjectMapper extends ObjectMapper {
public JsonObjectMapper() {
super();
this.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
this.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
this.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
}
春:3.2.4.RELEASE 傑克遜:2.1.2
編輯
該對象映射聲明在MVC消息轉換器中:
<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager">
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper" ref="jsonObjectMapper"/>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
而這正是我已經與命名策略的嘗試:
public class JsonPropertyNamingStrategy extends PropertyNamingStrategy {
public static final MyNamingStrategy MY_NAMING_STRATEGY = new MyNamingStrategy();
private static final LinkedHashMap<String, String> PROPERTIES = new LinkedHashMap<String, String>() {{
put("LinkedList", "resultList");
}};
public static class MyNamingStrategy extends PropertyNamingStrategyBase {
@Override
public String translate(String propertyName) {
if (propertyName == null) {
return null;
}
if (PROPERTIES.containsKey(propertyName)) {
return PROPERTIES.get(propertyName);
}
return propertyName;
}
}
}
我調試它,當它涉及到翻譯方法屬性名稱來之外的所有根元素。我擁有包含LinkedList
的所有內容,但LinkedList
未提供此方法。
你在哪裏接線這個ObjectMapper?這是正在使用的還是Spring默認的仍在使用?還有什麼你嘗試過'PropertyNamingStrategy'?最後一部分還不是很清楚。 (你只提到它不起作用)。 –
已編輯,請看看。 – user2219247
查看Jackson的來源''PropertyNamingStrategy'不會有幫助,因爲它僅用於屬性而不用於根類型。從源頭上看'RootNameLookup'正在處理翻譯,並且只允許使用註釋進行不同的命名,否則它將回退到類名。使用JAXB註釋時,傑克遜將使用這些元數據。 –