Search code examples
javajsonjson-lib

convert List<CustomObject> to json


i use json-lib to convert a java Object to json string,now i define a

List<CustomObject> list=...

i want to convert it to json string,but i got

[{},{},{}]

the CustomObject is defined as:

 class CustomObject{
     int id;
     int num;
 }

is there any way to get a correct string like:

[{'id':1,'num:3'},{'id':2,'num:4'}]

if i use struts2 to do it,it works.but i don`t know how it works,must i use struts2?


Solution

  • Your class should be somewhat like this:

          public class CustomObject{
         int id;
         int num;
    
    
         public int getId() {
            return id;
        }
    
    
        public void setId(int id) {
            this.id = id;
        }
    
    
        public int getNum() {
            return num;
        }
    
    
        public void setNum(int num) {
            this.num = num;
        }
    
    
        public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
            List<CustomObject> list=new ArrayList<CustomObject>();
            CustomObject c=new CustomObject();
            c.id=1;
            c.num=1;
            list.add(c);
            System.out.println(new ObjectMapper().writeValueAsString(list)); 
        }
     }
    

    You need to have getters and setters if you want to serialize or deserialize any object. Use jackson to covert to JSON.