json - Struts2 (2.3.34) 重命名 JSON 输出中的一些对象字段
问题描述
在 Struts2 中,我需要任意重命名来自我的List<CustomObject>
集合的 JSON 输出中的某些字段。
从 Struts 2.5.14 开始,有一种方法可以定义自定义 JsonWriter, http ://struts.apache.org/plugins/json/#customizing-the-output
但我的应用程序在 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
期望的结果:
{
"records": [
"renamedField1" : "data 1",
"field2" : "data 2"
]
}
Jackson 注释@JsonProperty
无效:
@JsonProperty("renamedField1")
private String field1;
解决方案
我的最终答案基于sark2323
关于直接使用 Jackson 的提示ObjectMapper
。
服务器端
public class MyAction {
private InputStream modifiedJson; // this InputStream action property
// will store modified Json
public InputStream getModifiedJson() {
return modifiedJson;
}
public void setModifiedJson(InputStream modifiedJson) {
this.modifiedJson = modifiedJson;
}
// Now the handler method
public String retrieveJson() throws Exception {
ObjectMapper mapper = new ObjectMapper();
List<Publication> records = service.getRecords();
String result = mapper.writeValueAsString(records);
modifiedJson = new ByteArrayInputStream(result.getBytes());
return SUCCESS;
}
}
struts.xml
<action name="retrieveJson" method="retrieveJson" class="myapp.MyAction">
<result type="stream">
<param name="contentType">text/plain</param>
<param name="inputName">modifiedJson</param>
</result>
</action>
结果是一个流(即纯字符串),因为我们想避免 Struts 的内部 JSON 编组,这会引入字符转义。Jackson 已经生成了一个 JSON 字符串,现在我们只是通过 Stream 方法将它作为纯字符串输出。
推荐阅读
- ios - SpriteKit 类别BitMask 问题
- reactjs - 在示例中显示 createRef 意外令牌错误的反应传单
- xamarin - 在 Azure Pipelines 上构建时,是否有可用版本的 MSBuild 列表可供选择?
- c - 如何在c中生成0到1之间的对称序列(每个部分的元素数量相同)?
- python - 根据 PEP8 标准和 python 换行技术分解字符串格式的代码行的最佳方法是什么?
- node.js - 如何在猫鼬中填充引用另一个模式的对象数组
- ios - 如何正确制作包含一些 viewControllers 的容器视图(以编程方式)?
- c# - 如何在哈希表中添加范围?
- gcc - 用于 MAJIQ 管道安装的 Clang 编译器和 gcc 问题
- nginx - ngx_http_script_compile 与 ngx_http_compile_complex_value