tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Tools and Libs > SOJO > Bean List to JSON

Bean List to JSON 

SOJO (Simplified Old Java Objects) is a Java framework which converts object graph into a specific structure or representation. This requires the library sojo-1.0.0.jar to be in classpath. The following example shows using JsonSerializer class. It converts the given bean list to JSON.

File Name  :  
com/bethecoder/tutorials/sojo/common/Student.java 
   
package com.bethecoder.tutorials.sojo.common;

public class Student {

  private String name;
  private int age;
  private String hobby;

  public Student() {
  }

  public Student(String name, int age, String hobby) {
    super();
    this.name = name;
    this.age = age;
    this.hobby = hobby;
  }

  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public int getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
  }
  public String getHobby() {
    return hobby;
  }
  public void setHobby(String hobby) {
    this.hobby = hobby;
  }
  
  public String toString() {
    return "Student[name = " + name + ", age = " + age + ", hobby = " + hobby + "]";
  }
}
   

File Name  :  
com/bethecoder/tutorials/sojo/tests/BeanList2JSON.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.sojo.tests;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import net.sf.sojo.interchange.Serializer;
import net.sf.sojo.interchange.json.JsonSerializer;

import com.bethecoder.tutorials.sojo.common.Student;

public class BeanList2JSON {

  /**
   @param args
   */
  public static void main(String[] argsthrows IOException {
    
    Student student = new Student("Sriram"2"Chess");
    Student student2 = new Student("Sudhakar"29"Painting");
    Student student3 = new Student("Charan"18"Reading books");
    List<Student> students = Arrays.asList(student, student2, student3);
    
    Serializer serializer = new JsonSerializer();
    String str = (Stringserializer.serialize(students);
    
    System.out.println("Generated JSON : \n");
    System.out.println(str);
  }
}
   

It gives the following output,
Generated JSON : 

[
  {
  	"~unique-id~":"0",
  	"hobby":"Chess",
  	"class":"com.bethecoder.tutorials.sojo.common.Student",
  	"name":"Sriram",
  	"age":2
  },
  
  {
  	"~unique-id~":"1",
  	"hobby":"Painting",
  	"class":"com.bethecoder.tutorials.sojo.common.Student",
  	"name":"Sudhakar",
  	"age":29
  },
  
  {
  	"~unique-id~":"2",
  	"hobby":"Reading books",
  	"class":"com.bethecoder.tutorials.sojo.common.Student",
  	"name":"Charan",
  	"age":18
  }
]



 
  


  
bl  br