Search code examples
jsonstruts2

Struts2 (2.3.34) Rename Some Object Fields in JSON Output


In Struts2, I need to arbitrarily rename some fields in the JSON output coming from my List<CustomObject> collection.

Starting with Struts 2.5.14 there is a way to define a custom JsonWriter, http://struts.apache.org/plugins/json/#customizing-the-output

But my app is in Struts 2.3.34.

Ex. of what I need:

struts.xml

<action name="retrieveJson" method="retrieveJson" class="myapp.MyAction">
    <result type="json">
    </result>       
</action>

Return List on Server-Side

public String retrieveJson() throws Exception {
    records = service.getRecords(); // This is a List<Record>
    return SUCCESS;
}

Example of Record Object

public class Record {
    String field1; // Getter/setters
    String field2;
}

JSON

{
   "records": [
       "field1" : "data 1",
       "field2" : "data 2"
   ]
}

Now I need to map/rename arbitrary fields: e.g. field1 -> renamedField1

Desired result:

{
   "records": [
       "renamedField1" : "data 1",
       "field2" : "data 2"
   ]
}

The Jackson annotation @JsonProperty had no effect:

@JsonProperty("renamedField1")
private String field1;

Solution

  • 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;
    }