Java-Web:Creating JSON from Java
This chapter introduces you to the basics of using creating JSON from Java. In the short lecture, we show you the code for creating JSON using first
javax.json, then using
The code is quite similar, but the APIs differ a little. The class names differ and the method names differs slightly. Also, javax.json uses a
org.json is based around the principle that JSON is just text. So for the org.json example, we use a simple
PrintWriter to write the JSON object to a file. The JSONObject is converted to text using an overloaded version of
toString(int indent), which takes an int argument for indentation steps.
This is a short example, for sure, but we wanted to give you a small introduction to producing JSON from Java and how to do it using two different APIs. We think you will find it useful to try out both APIs.
After reviewing the slides and watching the video lecture, move on to the exercises linked below. Also, as usual, make sure to read up on the external links for further reading.
In order to fully understand this chapter, we assume you have basic knowledge of JSON and Java. If you feel that you need to freshen up on SQL, we recommend our book Programming with Java and also the chapter on Java-Web:Introduction to JSON.
Lecture slides and videos
General - showing both javax.json and org.json for creating a JSON file
- Lecture slides (PDF) Creating JSON from Java (English)
- Channel for English version: Java - Create JSON (PDF)
- Channel for Swedish version: Java - Generera JSON (Swedish - one lecture divided into two videos)
- Source code for the lecture example: github.com/progund/java-web/tree/master/java-json/presentation-sources
Creating JSON (a JSON String) using org.json
- Lecture slides (PDF): Creating JSON using org.json (pdf)
- Source code for the lecture: github.com/progund/java-web/tree/master/java-json/org.json/creating
- Channel: Java - Creating with org.json (Eng)
Up next: Exercises!