我有一个方案可以将状态列表作为json返回,这在状态枚举(“我的枚举”如下)中可用
示例:-
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;
}
}
需要这样的输出:
[{id:“ 100”,名称:“ CREATED”},{id:“ 200”,名称:“ UPDATED”} ......] 我已经用List Of maps编写了查找方法来构建响应,是否有更好的方法或实用程序将Enum转换为具有Enum中所有可用属性的对象。
还有更好的方法吗?
答案 0 :(得分:1)
您可以使用Gson或Jackson之类的库来进行JSON序列化,并在其中实现自定义序列化。
class StatusSerializer implements JsonSerializer<Status> {
public JsonElement serialize(Status status, Type typeOfSrc, JsonSerializationContext context) {
JsonObject object = new JsonObject();
object.addProperty("ID", status.getId());
object.addProperty("name", status.getName());
return object;
}
}
然后按以下方式使用它:
Gson gson = new GsonBuilder()
.registerTypeAdapter(Status.class, new StatusSerializer())
.create();
String json = gson.toJson(Status.CREATED);
产生:
{"ID":"100","name":"CREATED"}
答案 1 :(得分:1)
您可以使用Jackson转换为JSON。只需包含@JsonFormat(shape = Shape.OBJECT) 在Enum声明中。这应该给你结果。
答案 2 :(得分:0)
Arrays.stream( Status.class.getEnumConstants() )
.map( e -> Map.of( "id", e.getId(), "name", e.getName() )
.collect( Collectors.toList() );
我正在移动设备上,无法进行测试,但是您了解了一般想法
答案 3 :(得分:0)
您可以在Java 8中使用Stream API。为了获得良好的性能,请使用并行。
List<Map<String, String>> list = Stream.of(Status.values()).parallel().map(temp -> {
Map<String, String> obj = new HashMap<String, String>();
obj.put("id", temp.getId());
obj.put("name", temp.getName());
return obj;
}).collect(Collectors.toList());