java - Jackson: Serialize comma separated string to json array -


currently have form below:

public class form {      private string listofitems;      public string getlistofitems() {         return listofitems;     }      public void setlistofitems(string listofitems) {         this.listofitems= listofitems;     }  } 

for instanse listofitems equals following string "1,2,3".

the goal serialize form following format:

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

it know how correctly such thing? know possible create custom serializer mark appropriate getter method it, @jsonserialize(using = somecustomserializer).

but not sure whether correct approach, default implementations exist.

if can edit 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();             (string s : listofitems.split(",")) {                 items.add(integer.parseint(s)); // may throw numberformatexception             }             return items;         }         return null;     } } 

by default jackson looks getters serializing. can override 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]} 

Comments