Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Return Enum objects with all properties from Enum values in Java

Tags:

java

enums

I have got a scenario to return list of status as json which are available in Status Enum, My Enum Looks below

Example:-

public enum Status {

CREATED("100", "CREATED"), UPDATED("200", "UPDATED"), DELETED("300", "DELETED");

private final String id;
private final String name;

private Status(String id, String name) {
    this.id = id;
    this.name = name;
}

public String getId() {
    return id;
}

public String getName() {
    return name;
}

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

public List<Map<String, String>> lookup() {
    List<Map<String, String>> list = new ArrayList<>();
    for (Status s : values()) {
        Map<String, String> map = new HashMap<>();
        map.put("ID", s.getId());
        map.put("name", s.getName());
        list.add(map);
    }
    return list;

}
}

need the output like this:

[{id:"100",name:"CREATED"},{id:"200", name:"UPDATED"}...] I have written lookup method with List Of maps to build the response, Is there any better way or utility to convert the Enum to Object with all the properties available in Enum.

Is there any better way to do this?

like image 611
Mahesh B Avatar asked May 17 '26 17:05

Mahesh B


1 Answers

You can use Jackson to convert to JSON. Just include @JsonFormat(shape = Shape.OBJECT) at Enum declaration. This should give you the result.

like image 90
akhan001 Avatar answered May 20 '26 07:05

akhan001