English 中文(简体)
JSON.simple - Customized Output
  • 时间:2024-09-17

JSON.simple - Customized Output


Previous Page Next Page  

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

Following example illustrates the above concept.

Example

import java.io.IOException;

import org.json.simple.JSONArray;
import org.json.simple.JSONAware;
import org.json.simple.JSONObject;

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")); 

      System.out.println(students);     
   }
}
class Student implements JSONAware {
   int rollNo;
   String name;
   Student(int rollNo, String name){
      this.rollNo = rollNo;
      this.name = name;
   }
   @Override
   pubpc String toJSONString() {
      StringBuilder sb = new StringBuilder();
      sb.append("{");
      sb.append("name");
      sb.append(":");
      sb.append(""" + JSONObject.escape(name) + """);
      sb.append(",");
      sb.append("rollNo");
      sb.append(":");
      sb.append(rollNo);
      sb.append("}");
      return sb.toString();
   }    
}

Output

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