fashuser
fashuser

Reputation: 1479

Jackson: Serialize comma separated string to json array

Currently I have form like below:

public class Form {

    private String listOfItems;

    public String getListOfItems() {
        return listOfItems;
    }

    public void setListOfItems(String listOfItems) {
        this.listOfItems= listOfItems;
    }

}

For instanse listOfItems equals to the following string "1,2,3".

The goal is to serialize this form to following format:

{
    "listOfItems": [1, 2, 3]
}

It would be good to know how to correctly do such thing? As I know it is possible to create some custom serializer then mark appropriate getter method with it, like this @JsonSerialize(using = SomeCustomSerializer).

But not sure whether it is correct approach, probably any default implementations already exist.

Upvotes: 2

Views: 6118

Answers (1)

Ghokun
Ghokun

Reputation: 3465

If you can edit your Form class:

public class Form {

    private String listOfItems;

    public String getListOfItems() {
        return listOfItems;
    }

    public void setListOfItems(String listOfItems) {
        this.listOfItems = listOfItems;
    }

    @JsonProperty("listOfItems")
    public List<Integer> getArrayListOfItems() {
        if (listOfItems != null) {
            List<Integer> items = new ArrayList();
            for (String s : listOfItems.split(",")) {
                items.add(Integer.parseInt(s)); // May throw NumberFormatException
            }
            return items;
        }
        return null;
    }
}

By default Jackson looks for getters for serializing. You can override this by using @JsonProperty annotation.

    ObjectMapper mapper = new ObjectMapper();
    Form form = new Form();
    form.setListOfItems("1,2,3");

    System.out.print(mapper.writeValueAsString(form));

Outputs:

{"listOfItems":[1,2,3]}

Upvotes: 1

Related Questions