JSON with Java - JSON (JavaScript Object Notation)

How to encode and decode JSON objects using Java?

Here you will learn about how to encode and decode JSON objects using Java programming language. Here’s how to start with preparing the environment to start our programming with Java for JSON.

Environment

It is must to have installed of any JSON module before you start with encoding and decoding JSON using Java. Download and install JSON.simple and have added the location of json-simple-1.1.1.jar file to the environment variable CLASSPATH.

Mapping between JSON and Java entities

JSON.simple maps entities from the left side to the right side while decoding or parsing, and maps entities from the right to the left while

JSON

Java

string

java.lang.String

number

java.lang.Number

true|false

java.lang.Boolean

null

null

array

java.util.List

object

java.util.Map

On decoding, the default concrete class of java.util.List is org.json.simple.JSONArray and the default concrete class of java.util.Map is org.json.simple.JSONObject.

How to encode JSON in Java?

You need to follow the following example to encode a JSON object using Java JSONObject which is a subclass of java.util.HashMap. Here there is no requirement of ordering is provided. If you need the strict ordering of elements, use JSONValue.toJSONString ( map ) method with ordered map implementation such as java.util.LinkedHashMap.
After compiling and executing the above program the following result will be generated –
Here’s another example that shows a JSON object streaming using Java JSONObject –
After compiling and executing the above program, below result will be produced.

Decoding JSON in Java

Below mentioned example describes how to use of JSONObject and JSONArray where JSONObject is a java.util.Map and JSONArray is a java.util.List, so you can access them with standard operations of Map or List.
After compiling and executing the above program, below result will be generated –

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

JSON (JavaScript Object Notation) Topics