- JSON.simple - Home
- JSON.simple - Overview
- JSON.simple - Environment Setup
- JSON.simple - JAVA Mapping
- Decoding Examples
- Escaping Special Characters
- JSON.simple - Using JSONValue
- JSON.simple - Exception Handling
- JSON.simple - Container Factory
- JSON.simple - Content Handler
- Encoding Examples
- JSON.simple - Encode JSONObject
- JSON.simple - Encode JSONArray
- Merging Examples
- JSON.simple - Merging Objects
- JSON.simple - Merging Arrays
- Combination Examples
- JSON.simple - Primitive, Object, Array
- JSON.simple - Primitive, Map, List
- Primitive, Object, Map, List
- Customization Examples
- JSON.simple - Customized Output
- Customized Output Streaming
- JSON.simple Useful Resources
- JSON.simple - Quick Guide
- JSON.simple - Useful Resources
- JSON.simple - Discussion
JSON.simple - Customized Output
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 {
public static void main(String[] args) throws IOException {
JSONArray students = new JSONArray();
students.add(new Student(1,"Robert"));
students.add(new Student(2,"Julia"));
System.out.println(students);
}
}
class Student implements JSONAware {
int rollNo;
String name;
Student(int rollNo, String name){
this.rollNo = rollNo;
this.name = name;
}
@Override
public 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:"Julia",rollNo:2}]
Advertisements