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
Customized Output Streaming
JSON.simple - Customized Output Streaming
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