sparrow sparrow - 7 months ago 19
Java Question

Jackson Annotation Option to remove property name when serializing

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

Answer

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;
    }
}