Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserializing a field named "class" into a POJO using Jackson

This may look a dumb question, but I would like to deserialize a JSON object to a POJO MyObject with a field named class, which is a reserved keyword in Java... If possible, I'd like to keep MyObject Jackson/Json/Whatever-dependency free.

Do I need to add a (standard or Jackson-specific) Java annotation to my class field member to handle this? Or is there another work-around to have a "pure" java object? I can configure the Jackson object mapper if needed.

public class MyObject {
  public String field1;
  public String class; // FAIL
}
like image 786
Laurent Grégoire Avatar asked Oct 29 '25 05:10

Laurent Grégoire


1 Answers

Since class is a reserved Java keyword, you cannot use it directly. If you simply want the generated JSON to have it, use @JsonProperty and set its value attribute.

public class MyObject {
    public String field1;

    @JsonProperty(value = "class")
    public String clazz; 
}
like image 111
Sotirios Delimanolis Avatar answered Oct 31 '25 20:10

Sotirios Delimanolis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!