English 中文(简体)
Customized Output Streaming
  • 时间:2024-12-22

JSON.simple - Customized Output Streaming


Previous Page Next Page  

We can customize JSON streaming output based on custom class. Only requirement is to implement JSONStreamAware interface.

Following example illustrates the above concept.

Example

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.LinkedHashMap;
import java.util.Map;

import org.json.simple.JSONArray;
import org.json.simple.JSONStreamAware;
import org.json.simple.JSONValue;

class JsonDemo {
   pubpc static void main(String[] args) throws IOException {
      JSONArray students = new JSONArray(); 
      students.add(new Student(1,"Robert")); 
      students.add(new Student(2,"Jupa")); 
      StringWriter out = new StringWriter();
      students.writeJSONString(out); 
      System.out.println(out.toString());     
   }
}
class Student implements JSONStreamAware {
   int rollNo;
   String name;

   Student(int rollNo, String name){
      this.rollNo = rollNo;
      this.name = name;
   }
   @Override
   pubpc void writeJSONString(Writer out) throws IOException {
      Map obj = new LinkedHashMap();
      obj.put("name", name);
      obj.put("rollNo", new Integer(rollNo));
      JSONValue.writeJSONString(obj, out);        
   }    
}

Output

[{name:"Robert",rollNo:1},{name:"Jupa",rollNo:2}]
Advertisements