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 - Encode JSONObject
JSON.simple - Encode JSONObject
Using JSON.simple, we can encode a JSON Object using following ways −
Encode a JSON Object - to String − Simple encoding.
Encode a JSON Object - Streaming − Output can be used for streaming.
Encode a JSON Object - Using Map − Encoding by preserving the order.
Encode a JSON Object - Using Map and Streaming − Encoding by preserving the order and to stream.
Following example illustrates the above concepts.
Example
import java.io.IOException; import java.io.StringWriter; import java.util.LinkedHashMap; import java.util.Map; import org.json.simple.JSONObject; import org.json.simple.JSONValue; class JsonDemo { pubpc static void main(String[] args) throws IOException { JSONObject obj = new JSONObject(); String jsonText; obj.put("name", "foo"); obj.put("num", new Integer(100)); obj.put("balance", new Double(1000.21)); obj.put("is_vip", new Boolean(true)); jsonText = obj.toString(); System.out.println("Encode a JSON Object - to String"); System.out.print(jsonText); StringWriter out = new StringWriter(); obj.writeJSONString(out); jsonText = out.toString(); System.out.println(" Encode a JSON Object - Streaming"); System.out.print(jsonText); Map obj1 = new LinkedHashMap(); obj1.put("name", "foo"); obj1.put("num", new Integer(100)); obj1.put("balance", new Double(1000.21)); obj1.put("is_vip", new Boolean(true)); jsonText = JSONValue.toJSONString(obj1); System.out.println(" Encode a JSON Object - Preserving Order"); System.out.print(jsonText); out = new StringWriter(); JSONValue.writeJSONString(obj1, out); jsonText = out.toString(); System.out.println(" Encode a JSON Object - Preserving Order and Stream"); System.out.print(jsonText); } }
Output
Encode a JSON Object - to String {"balance":1000.21,"is_vip":true,"num":100,"name":"foo"} Encode a JSON Object - Streaming {"balance":1000.21,"is_vip":true,"num":100,"name":"foo"} Encode a JSON Object - Preserving Order {"name":"foo","num":100,"balance":1000.21,"is_vip":true} Encode a JSON Object - Preserving Order and Stream {"name":"foo","num":100,"balance":1000.21,"is_vip":true}Advertisements