简体   繁体   中英

map json string to enum

I have the following class and enum s:

import lombok.Data;
// other imports...

@Data
public class MapTest{
    private MyFirstEnum myFirstEnum;
    private MySecondEnum mySecondEnum;
}

public enum MyFirstEnum{
    MY_FIRST_ENUM1,
    MY_FIRST_ENUM2
}

public enum MySecondEnum {
    MY_SECOND_ENUM1,
    MY_SECOND_ENUM2
}

and this spring controller:

@PostMapping("/testMap")
@ResponseBody
public void TestMap(@RequestBody MapTest mapTest){

}

Since an enum can be looked up by its name what I would like to do is to post a json to the controller and that the appropriate props will be serialized by their name:

{
    "myFirstEnum": "MY_FIRST_ENUM1",
    "mySecondEnum": "MY_SECOND_ENUM2"
}

I've tried to set up a @JsonDeserialize but i couldn't get the type of the enum inside the overridden function:

// what type should i use here?
public static class StringToEnum extends JsonDeserializer<???> {
    // how do i get the type of the current enum?
    @Override
    public ??? deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        ??? res = Enum.valueOf(p.getText());
        return res;
    }
}

Update: I've failed to mention that i'm using lombok's @data attribute for automatically generating getters and setters, which doesn't work well with enum bindings (not sure why).
I guess that laziness comes with a price.

It should be serialized automatically via jackson but you can force it via @JsonCreator
Redefine your enums as

public enum MyFirstEnum{
    MY_FIRST_ENUM1,
    MY_FIRST_ENUM2;

    @JsonCreator
    public static MyFirstEnum fromString(String raw) {
        return MyFirstEnum.valueOf(raw.toUpperCase());
    }
}

Similarly define your second enum as well in the similar manner.

Imp Note (Mandatory)

MapTest should have public setter / getter for both enums (if declared private, preferred), or declare them public (should be avoided, not preferred)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM