Home > other >  Retrieve data of a enum to a json object
Retrieve data of a enum to a json object

Time:12-11

I have the following code and I need to output a json object with key value pairs.

public enum General implements Catalogue {
    TOUR("3D Tour"),
    VIDEOS("Videos"),
    PHOTOS_ONLY("Photos Only"),
    PRICE_REDUCED("Price Reduced"),
    FURNISHED("Furnished"),
    LUXURY("Luxury");

    private final String value;

    General(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    public static List<String> valuesList() {
        return Arrays.stream(General.values()).map(General::getValue).collect(Collectors.toList());
    }
}

My response should be like this enter image description here

CodePudding user response:

This method inside your Enum will return General jsonArray alone. You need to construct the final json on top of it.

public static List<Map<String, String>> jsonList() {
        return Arrays.stream(General.values()).map(e -> {
            Map<String, String> m = new HashMap<>();
            m.put("text", e.name());
            m.put("value", e.getValue());
            return m;
        }).collect(Collectors.toList());
    }

Having pojo class with text & value will be good one, instead of putting in map.

public class GeneralPojo {
private String text;
private String value;

public GeneralPojo(String text, String value) {
    this.text = text;
    this.value = value;
}

public String getText() {
    return text;
}

public void setText(String text) {
    this.text = text;
}

public String getValue() {
    return value;
}

public void setValue(String value) {
    this.value = value;
}

}

If using the above Pojo, then your method should be

public static List<GeneralPojo> jsonObjList() {
    return Arrays.stream(General.values()).map(e -> new GeneralPojo(e.name(), e.getValue()))
            .collect(Collectors.toList());
}
  • Related