0

I face the next problem:

I have properties on BE side, which I can get and set via handler. I use enum to set properties, and bean class to get. Now I need to duplicate properties names, I want to avoid it.

public enum ExampleEnum {

    APPLE("_apple"),
    PEAR("_pear"),
    PINEAPPLE("_pineapple");

    private final String name;

    ExampleEnum(String name) {
        this.name = name;
    }

    @Override
    public String getName() {
        return name;
    }
}

@Data
@With
@AllArgsConstructor
public class EnumBean {

    @SerializedName("_apple")
    String apple;
    @SerializedName("_pear")
    String pear;
    @SerializedName("_pineapple")
    String pineapple;

}

public interface PropertiesService {

    EnumBean getPropertiesViaBE();
    void setPropertyViaBE(ExampleEnum property, String value);

}

Now I have to support consistency in both ways between these classes.

  • Does this answer your question? [serialize and deserialize enum with Gson](https://stackoverflow.com/questions/16740078/serialize-and-deserialize-enum-with-gson) – Jean-Baptiste Yunès Apr 16 '21 at 09:57

1 Answers1

0

I'm not sure this is what you want to achive but I'll guess:

You want to return a json object that basically contains a mapping of the name attribute to the enum name, e.g. something like this:

{
   "_apple": "APPLE",
   "_pear": "PEAR",
   "_pineapple":"PINEAPPLE"
}

On a side note I'm not sure why you'd need this as a simple list would probably be enough to get the available enums but maybe I guessed wrong and you need to add more info. In any case you could build on the following.

To generate a json string like the above you don't need a POJO. Most json generators and parsers support generic types, e.g. maps and collections. Thus you could just build a map:

Map<String, String> map = Arrays.stream(ExampleEnum.values())
                                .collect(Collectors.toMap(e -> e.getName(), 
                                                          e -> e.name()));

Then just serialize that map to json and you should get a string like the above.

Thomas
  • 87,414
  • 12
  • 119
  • 157
  • I hold this bean class for backend response deserialisation, so I think I need this class. – Shilko2013 Apr 16 '21 at 10:09
  • You can deserialize into a `Map` as well. However, I have the feeling we have a [xy-problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) here, so could you edit your question and elaborate on what you want to achieve? – Thomas Apr 16 '21 at 10:15
  • @Shilko2013 you could still do it like above especially if you maintain that map internally and use the property values as the map values. You might want to use the enum as the key though and in that case your json framework would need some information on how to map the enum values to their names and vice versa. So try `Map getPropertiesViaBE();` and return an immutable map, e.g. via `Map.copyOf(yourInternalMap)`. – Thomas Apr 16 '21 at 11:54