简体   繁体   中英

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. 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 ( ie 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM