3

I have this POJO:

public class SetPoint {

    private String tagName;
    //more fields

   //getters and setters

}

I'm getting SetPoints from a REST API, do something with them and then send them again. Problem is that I want deserialize a SetPoint from a JSON like:

{
    "tagnameOpc" : "6GH783",
    //more fields
}

But when I send them, I want serialize a SetPoint as:

{
    "tagName" : "6GH783"
    //more fields
}

I mean, I want the property tagName to be named different in each case.

Is this possible?

Héctor
  • 24,444
  • 35
  • 132
  • 243

3 Answers3

8

Try using a different JsonProperty annotation for the getter and the setter. E.g.

@JsonProperty("tagnameOpc")
void setTagName(String name)

@JsonProperty("tagName")
String getTagName()

If that doesn't work try with an extra setter

@JsonIgnore
void setTagName(String name)

@JsonProperty("tagnameOpc")
void setTagNameOpc(String name) {
    setTagName(name);
}

@JsonProperty("tagName")
String getTagName()
Manos Nikolaidis
  • 21,608
  • 12
  • 74
  • 82
  • Setters are for Deserialization of a Json string to an object. They make non-public fields deserializable. Getters are for Serialization of an object to Json. They make non-public fields serializable – Ikhiloya Imokhai Apr 30 '19 at 11:54
1

Jackson mix-in annotations might help.

You would use the SetPoint class twice, but write a different mix-in class for each serialisation/deserialisation format, and then configure the ObjectMapper separately for each case.

Sean Reilly
  • 21,526
  • 4
  • 48
  • 62
0

Assuming jsonObject is a JSONObject containing your json:

jsonObject.put("tagName", jsonObject.remove("tagnameOpc"));

From JSonObject documentation: jsonObject.remove(key) returns the value that was associated with that key, or null if there was no value.

AlbertoD
  • 146
  • 1
  • 9
  • I'm using `MappingJackson2HttpMessageConverter` with Spring RestTemplate, so actually I don't work directly with `JSONObject`. Thanks, anyway – Héctor Nov 10 '15 at 09:50