I am working on how to serialised a POJO into a json string. I am using the jackson library and have run into a problem.
A value in the json object can either be a string or a string array like so…
{"mimeTypes":"all"}
or
{"mimeTypes":["application/pdf", "application/msword"]}
This is my approach at the moment
@JsonIgnore
private String mimeTypes;
@JsonIgnore
private String[] mimeTypesArray;
@JsonRawValue
@JsonProperty("integration/enabled-mime-types")
private String mimeType;
public void setMimeTypes(String mimeTypes) {
this.mimeTypes = mimeTypes;
mimeType = mimeTypes;
}
public void setMimeTypes(String[] mimeTypes) {
this.mimeTypesArray = mimeTypes;
try {
JSONArray jsonArray = new JSONArray(mimeTypes);
this.mimeType = jsonArray.toString();
} catch (JSONException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
Basically I have a field for the string, a field for the string array, and a field for the string I want to add to the json object. I serialise on the setter so the object mapper doesn’t have to choose which field to use.
This feels like a hacky way of doing things. Would there be a better solution? I have been reading about using jackson views but I am not sure if this is possible for my problem.
I haven’t tested it, but I’d try adding a dedicated method for computing what should be serialized:
This way, if you have just one item in the array, the serialized value will be just the item. Otherwise the whole array will be serialized.
Note that it is a bad practise having two setters with the same name and different signatures. AFAIK that violates the Java Beans specification.
Perhaps you could use a vararg method here to replace the two setters (but I don’t know how this goes together with Java Beans specification):