1. BACKEND
In my backend (SpringBoot) I am sending list of enums:
@RequestMapping("getMyEnum")
public List<MyEnum> getMyEnum() {
return Arrays.asList(MyEnum.values());
}
Here is MyEnum:
public enum MyEnum {
A("bla1"),
B("bla2");
private String value;
MyEnum(String value) {
...
2. FRONTEND
In frontend (angular2) I am receiving this list in my ng2 component:
MY_ENUMS: MyEnum[];
...
this.http.get('/util/getClassifications')
.map(response => response.json())
.subscribe(myEnums => {
this.MY_ENUMS = myEnums;
});
Here is class MyEnum:
export class MyEnum {
value: string;
}
3. RESULT
After running the code:
MY_ENUMS contains ["A", "B"]
But I would expect:
MY_ENUMS will contains [ "A" : { "value" : "bla1"},
"B" : { "value" : "bla2"}]
Per default Jackson
(the JSON mapper which is used in Spring Boot) serializes only the enum names. To adapt your enum serialization - and treat it as every other object - add to your enum the following JsonFormat
annotation and it will map all properties of the enum as well.
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum MyEnum
Update
Make sure your enum provides all getters.
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum MyEnum {
A("bla1", 1),
B("bla2", 2);
private String valueA;
private long valueB;
MyEnum(String valueA, long valueB) {
this.valueA = valueA;
this.valueB = valueB;
}
public String getValueA() {
return valueA;
}
public long getValueB() {
return valueB;
}
}
You can test you serialization with
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(MyEnum.A));
The result is
{"valueA":"bla1","valueB":1}