Good day all, I would like to remove the property name when Serializing a Pojo to json. I have the following class
public class Field {
private List<SubFieldItems> subFieldItems;
public List<SubFieldItems> getSubFieldItems() {
return subFieldItems;
}
public void setSubFieldItems(List<SubFieldItems> subFieldItems) {
this.subFieldItems = subFieldItems;
}
}
and the SubFieldItems class:
public class SubFieldItems {
@JsonPropertyOrder
private String name;
private List<String> items;
public SubFieldItems(String name, List<String> items) {
this.name = name;
this.items = items;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getItems() {
return items;
}
public void setItems(List<String> items) {
this.items = items;
}
//tried doing this
/* @JsonValue
@Override
public String toString() {
return "{" +
" \"name\":" + "\"" + name + "\"" +
",\" items\":" + items +
'}';
}*/
}
when i serialize, the json Output is
{
"field": {
"subFieldItems": [
{
"name": "brands",
" items": []
}
]
}
}
but i want to have the subFieldItems values without the property name like this:
{
"field": {
[
{
"name": "brands",
" items": []
}
]
}
}
What Jackson annotation can i use, i have tried using @JsonValue as in the toString method to force that like in the comments, but i keep getting weird results. Please Any help is appreciated. Thanks
@JsonIgnoreProperties annotation is used at the class level to ignore fields during serialization and deserialization. The properties that are declared in this annotation will not be mapped to the JSON content.
@JsonProperty is used to mark non-standard getter/setter method to be used with respect to json property.
@JsonIgnore is used to ignore the logical property used in serialization and deserialization. @JsonIgnore can be used at setters, getters or fields. If you add @JsonIgnore to a field or its getter method, the field is not going to be serialized.
The JSON you want is invalid, maybe this is what you want:
{
"field": [
{
"name": "brands",
"items": []
}
]
}
(Note that I've removed the brace after "field":
, as well as its matching closing brace).
In this case, you might find @JsonValue
annotation useful:
@JsonValue
: per-property marker to indicate that the POJO should serialization is to be done using value of the property, often a java.lang.String (like annotation toString() method).
Try this:
public class Field {
private List<SubFieldItems> subFieldItems;
@JsonValue
public List<SubFieldItems> getSubFieldItems() {
return subFieldItems;
}
public void setSubFieldItems(List<SubFieldItems> subFieldItems) {
this.subFieldItems = subFieldItems;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With