JSON.simple Tutorial
Selected Reading
- JSON.simple - Discussion
- JSON.simple - Useful Resources
- JSON.simple - Quick Guide
- Customized Output Streaming
- JSON.simple - Customized Output
- Primitive, Object, Map, List
- JSON.simple - Primitive, Map, List
- JSON.simple - Primitive, Object, Array
- JSON.simple - Merging Arrays
- JSON.simple - Merging Objects
- JSON.simple - Encode JSONArray
- JSON.simple - Encode JSONObject
- JSON.simple - Content Handler
- JSON.simple - Container Factory
- JSON.simple - Exception Handling
- JSON.simple - Using JSONValue
- Escaping Special Characters
- JSON.simple - JAVA Mapping
- JSON.simple - Environment Setup
- JSON.simple - Overview
- JSON.simple - Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
JSON.simple - Customized Output
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 { 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