2

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.

fashuser
  • 2,152
  • 3
  • 29
  • 51
  • 1
    Check this: http://stackoverflow.com/questions/5245840/how-to-convert-string-to-jsonobject-in-java – kunpapa Jan 29 '16 at 11:40

1 Answers1

1

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]}
Ghokun
  • 3,345
  • 3
  • 26
  • 30