I am working on an application where I want to convert string object coming from data api to json object.Now, I converted string object to json but there is a problem. My pojo class has multiple fields with corresponding getters and setters one of them is "filterName" and it looks like
@SerializedName(value="cellFilter", alternate="tissueFilter")
private String filterName;
What it does is it extracts the value associated with "cellFilter" and "tissueFilter". I am not sure if its an optimized way to retire the data using the same field. Also, I want to use that same field to retrieve another value and I don't know how to do that ( i.e I want to use filterName to get the values of tissueFilter, cellFilter and applicationFilter ).
data object looks like as following Note - there are 3 strings for tissueFilter, cellFilter and applicationFilter which comes from data api. After converting them in java objects they look like this,
tissufilter
{
"url": "xyz",
"sortOrder": 8,
"imageId": "1111",
"tissueFilter": "Heart"
}
cellFilter
{
"url": "xyz",
"sortOrder": 6,
"imageId": "2222",
"cellFilter": "Pancreas"
}
and applicationFilter
{
"applicationFilter": "c56",
"url": "xyz",
"sortOrder": 1,
"imageId": "3333",
}
Thank you
CodePudding user response:
If Jackson JSON library is used for serializing/deserialing JSON data, @JsonAlias
annotation should be applied to deserialize the field which may have different names:
@Data
class Pojo {
private String url;
private int orderId;
private String imageId;
@JsonAlias({"applicationFilter", "cellFilter", "tissueFilter"})
private String filter;
}
After deserialization of the mentioned JSON snippets, the field filter
should be set to appropriate value defined as "applicationFilter"
, etc.
However, it seems that Gson is used in the question, and its @SerializedName
also allows for multiple versions in alternate
parameter:
@Data
class PojoForGson {
private String url;
private int orderId;
private String imageId;
@SerializedName(value = "cellFilter" alternate = {"applicationFilter", "tissueFilter"})
private String filter;
}