【问题标题】:Retrieve data of a enum to a json object将枚举的数据检索到 json 对象
【发布时间】:2022-01-14 22:23:48
【问题描述】:

我有以下代码,我需要输出一个带有键值对的json对象。

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

我的回复应该是这样的

【问题讨论】:

  • 无论如何,您需要保留一个带有字段文本和值的 pojo 类来实现这一点。

标签: java json enums


【解决方案1】:

Enum 中的此方法将单独返回 General jsonArray。你需要在它之上构建最终的 json。

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

使用textvalue 开设pojo 课程会是一个不错的选择,而不是放入地图。

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

}

如果使用上面的Pojo,那么你的方法应该是

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

【讨论】:

  • 你能举一个 pojo 类的例子吗?
  • 用新的 pojoClass 更新了答案。
猜你喜欢
  • 1970-01-01
  • 2022-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-23
  • 2015-09-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多