How to change a field name in JSON using Jackson
I'm using jackson to convert an object of mine to json. The object has 2 fields:
@Entity
public class City {
@id
Long id;
String name;
public String getName() { return name; }
public void setName(String name){ this.name = name; }
public Long getId() { return id; }
public void setName(Long id){ 开发者_如何转开发this.id = id; }
}
Since I want to use this with the jQuery auto complete feature I want 'id' to appear as 'value' in the json and 'name' to appear as 'label'. The documentation of jackson is not clear on this and I've tried every annotation that even remotely seems like it does what I need but I can't get name
to appear as label
and id
to appear as value
in the json.
Does anyone know how to do this or if this is possible?
Have you tried using @JsonProperty?
@Entity
public class City {
@id
Long id;
String name;
@JsonProperty("label")
public String getName() { return name; }
public void setName(String name){ this.name = name; }
@JsonProperty("value")
public Long getId() { return id; }
public void setId(Long id){ this.id = id; }
}
Be aware that there is org.codehaus.jackson.annotate.JsonProperty
in Jackson 1.x and com.fasterxml.jackson.annotation.JsonProperty
in Jackson 2.x. Check which ObjectMapper you are using (from which version), and make sure you use the proper annotation.
Jackson
If you are using Jackson, then you can use the @JsonProperty
annotation to customize the name of a given JSON property.
Therefore, you just have to annotate the entity fields with the @JsonProperty
annotation and provide a custom JSON property name, like this:
@Entity
public class City {
@Id
@JsonProperty("value")
private Long id;
@JsonProperty("label")
private String name;
//Getters and setters omitted for brevity
}
JavaEE or JakartaEE JSON-B
JSON-B is the standard binding layer for converting Java objects to and from JSON. If you are using JSON-B, then you can override the JSON property name via the @JsonbProperty
annotation:
@Entity
public class City {
@Id
@JsonbProperty("value")
private Long id;
@JsonbProperty("label")
private String name;
//Getters and setters omitted for brevity
}
There is one more option to rename field:
Jackson MixIns.
Useful if you deal with third party classes, which you are not able to annotate, or you just do not want to pollute the class with Jackson specific annotations.
The Jackson documentation for Mixins is outdated, so this example can provide more clarity. In essence: you create mixin class which does the serialization in the way you want. Then register it to the ObjectMapper:
objectMapper.addMixIn(ThirdParty.class, MyMixIn.class);
精彩评论