首页 > 解决方案 > 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;

标签: jsonstruts2

解决方案


我的最终答案基于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 方法将它作为纯字符串输出。


推荐阅读