[英]How to map pojo class's field to string object returning from API
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. 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
我的 pojo class 有多个字段,对应的 getter 和 setter 其中之一是“filterName”,它看起来像
@SerializedName(value="cellFilter", alternate="tissueFilter")
private String filterName;
What it does is it extracts the value associated with "cellFilter" and "tissueFilter".它的作用是提取与“cellFilter”和“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 ( ie I want to use filterName to get the values of tissueFilter, cellFilter and applicationFilter ).
另外,我想使用同一个字段来检索另一个值,但我不知道该怎么做(即我想使用 filterName 来获取 organizationFilter、cellFilter 和 applicationFilter 的值)。
data object looks like as following Note - there are 3 strings for tissueFilter, cellFilter and applicationFilter which comes from data api.数据 object 如下所示 注意 - 组织过滤器、细胞过滤器和应用过滤器有 3 个字符串,它们来自数据 api。 After converting them in java objects they look like this,
在 java 对象中转换它们后,它们看起来像这样,
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谢谢
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:如果 Jackson JSON 库用于序列化/反序列化 JSON 数据,则应应用
@JsonAlias
注释可能具有不同名称的字段来反序列化:
@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.在对提到的 JSON 片段进行反序列化后,应将字段
filter
设置为定义为"applicationFilter"
等的适当值。
However, it seems that Gson is used in the question, and its @SerializedName
also allows for multiple versions in alternate
parameter:但是,问题中似乎使用了 Gson ,并且其
@SerializedName
还允许在alternate
参数中使用多个版本:
@Data
class PojoForGson {
private String url;
private int orderId;
private String imageId;
@SerializedName(value = "cellFilter" alternate = {"applicationFilter", "tissueFilter"})
private String filter;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.