ฉันจะ deserialize สตริง JSON ที่มีค่า enum ที่ไม่คำนึงถึงตัวพิมพ์เล็กและใหญ่ได้อย่างไร (โดยใช้ Jackson Databind)
สตริง JSON:
[{"url": "foo", "type": "json"}]
และ Java POJO ของฉัน:
public static class Endpoint {
public enum DataType {
JSON, HTML
}
public String url;
public DataType type;
public Endpoint() {
}
}
ในกรณีนี้การ deserializing JSON ด้วย"type":"json"
จะล้มเหลวในกรณีที่ได้"type":"JSON"
ผล แต่ฉันต้องการ"json"
ทำงานด้วยเพื่อเหตุผลในการตั้งชื่อ
การทำให้ POJO เป็นอนุกรมยังส่งผลให้เป็นตัวพิมพ์ใหญ่ "type":"JSON"
ฉันคิดว่าจะใช้@JsonCreator
และ @JsonGetter:
@JsonCreator
private Endpoint(@JsonProperty("name") String url, @JsonProperty("type") String type) {
this.url = url;
this.type = DataType.valueOf(type.toUpperCase());
}
//....
@JsonGetter
private String getType() {
return type.name().toLowerCase();
}
และมันได้ผล แต่ฉันสงสัยว่ามีโซลูทูออนที่ดีกว่าหรือไม่เพราะมันดูเหมือนแฮ็คสำหรับฉัน
ฉันยังสามารถเขียน deserializer ที่กำหนดเองได้ แต่ฉันมี POJO ที่แตกต่างกันมากมายที่ใช้ enums และมันยากที่จะดูแลรักษา
มีใครพอจะแนะนำวิธีที่ดีกว่าในการทำให้เป็นอนุกรมและ deserialize enums ด้วยหลักการตั้งชื่อที่เหมาะสมได้ไหม
ฉันไม่ต้องการให้ enums ของฉันใน java เป็นตัวพิมพ์เล็ก!
นี่คือรหัสทดสอบบางส่วนที่ฉันใช้:
String data = "[{\"url\":\"foo\", \"type\":\"json\"}]";
Endpoint[] arr = new ObjectMapper().readValue(data, Endpoint[].class);
System.out.println("POJO[]->" + Arrays.toString(arr));
System.out.println("JSON ->" + new ObjectMapper().writeValueAsString(arr));