Struts2(2.3.34)重命名JSON输出中的某些对象字段 [英] Struts2 (2.3.34) Rename Some Object Fields in JSON Output
问题描述
在Struts2中,我需要随意重命名来自我的List<CustomObject>
集合的JSON输出中的某些字段.
In Struts2, I need to arbitrarily rename some fields in the JSON output coming from my List<CustomObject>
collection.
从Struts 2.5.14开始,可以定义自定义JsonWriter, http://struts.apache.org/plugins/json/#customizing-输出
Starting with Struts 2.5.14 there is a way to define a custom JsonWriter, http://struts.apache.org/plugins/json/#customizing-the-output
但是我的应用程序在Struts 2.3.34中.
But my app is in Struts 2.3.34.
例如我需要的东西:
struts.xml
<action name="retrieveJson" method="retrieveJson" class="myapp.MyAction">
<result type="json">
</result>
</action>
服务器端返回列表
public String retrieveJson() throws Exception {
records = service.getRecords(); // This is a List<Record>
return SUCCESS;
}
记录对象示例
public class Record {
String field1; // Getter/setters
String field2;
}
JSON
{
"records": [
"field1" : "data 1",
"field2" : "data 2"
]
}
现在我需要映射/重命名任意字段:例如field1 -> renamedField1
Now I need to map/rename arbitrary fields: e.g. field1 -> renamedField1
所需结果:
{
"records": [
"renamedField1" : "data 1",
"field2" : "data 2"
]
}
Jackson批注@JsonProperty
无效:
The Jackson annotation @JsonProperty
had no effect:
@JsonProperty("renamedField1")
private String field1;
推荐答案
也许您可以使用注释@JsonProperty("renamedField1"),但是您需要使用杰克逊对象映射器来映射该对象,以获得预期的结果,这里有一个示例如何使用杰克逊对象映射器
Maybe you can use the annotation @JsonProperty("renamedField1") but you need to map the object using the jackson Object mapper in order to obtain the expected result, here you have an example how to use the jackson object mapper
public String retrieveJson() throws Exception {
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(service.getRecords());
return json;
}
这篇关于Struts2(2.3.34)重命名JSON输出中的某些对象字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!