Parsing JSON With Java 8 Without Dependencies

While working with JSON we often need to parse the JSON into an object, or Map, or List, or to a custom object as well.  To parse the JSON we have to use a dependency to process it easily.

But, starting with JDK 8u60+ the built-in Nashorn engine is capable to convert JSON content into java.util.Map or java.util.List. No external dependencies are required for parsing.

Here is an example with sample JSON. You can follow the below steps.

  1. Copy the below JSON into a file “test.json” and place it inside your java project.
{
	"page": "1",
	"per_page": 10,
	"total": 23,
	"total_pages": 3,
	"data": [
		{
			"competition": "UEFA Champions League",
			"year": 2014,
			"round": "GroupG",
			"team1": "Chelsea",
			"team2": "Schalke 04",
			"team1goals": "1",
			"team2goals": "1"
		},
		{
			"competition": "UEFA Champions League",
			"year": 2014,
			"round": "GroupG",
			"team1": "Chelsea",
			"team2": "NK Maribor",
			"team1goals": "6",
			"team2goals": "0"
		},
		{
			"competition": "UEFA Champions League",
			"year": 2014,
			"round": "GroupG",
			"team1": "Chelsea",
			"team2": "Sporting CP",
			"team1goals": "3",
			"team2goals": "1"
		},
		{
			"competition": "UEFA Champions League",
			"year": 2014,
			"round": "R16",
			"team1": "Chelsea",
			"team2": "Paris Saint-Germain",
			"team1goals": "1",
			"team2goals": "1"
		},
		{
			"competition": "English Premier League",
			"year": 2014,
			"round": "",
			"team1": "Chelsea",
			"team2": "Leicester City",
			"team1goals": "2",
			"team2goals": "0"
		},
		{
			"competition": "English Premier League",
			"year": 2014,
			"round": "",
			"team1": "Chelsea",
			"team2": "Swansea City",
			"team1goals": "4",
			"team2goals": "2"
		},
		{
			"competition": "English Premier League",
			"year": 2014,
			"round": "",
			"team1": "Chelsea",
			"team2": "Aston Villa",
			"team1goals": "3",
			"team2goals": "0"
		},
		{
			"competition": "English Premier League",
			"year": 2014,
			"round": "",
			"team1": "Chelsea",
			"team2": "Arsenal",
			"team1goals": "2",
			"team2goals": "0"
		},
		{
			"competition": "English Premier League",
			"year": 2014,
			"round": "",
			"team1": "Chelsea",
			"team2": "Queens Park Rangers",
			"team1goals": "2",
			"team2goals": "1"
		},
		{
			"competition": "English Premier League",
			"year": 2014,
			"round": "",
			"team1": "Chelsea",
			"team2": "West Bromwich Albion",
			"team1goals": "2",
			"team2goals": "0"
		}
	]
}

2. Create a class “JSONParser.java” and put the below code inside it.

package com.codersdesks.json;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;
import java.util.Map;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import org.junit.Before;
import org.junit.Test;

public class JSONParser {
	
	private ScriptEngine scriptEngine;
	private String json;

	@Before
	public void setup() throws IOException {
		ScriptEngineManager sem = new ScriptEngineManager();
		this.scriptEngine = sem.getEngineByName("javascript");
		File file = new File("test.json");
		this.json = new String(Files.readAllBytes(file.toPath()));
	}

	@Test
	public void parse() throws ScriptException {
		String script = "Java.asJSONCompatible(" + this.json + ")";
		Object result = this.scriptEngine.eval(script);
		Map contents = (Map) result;
		
		contents.forEach((k,v) ->{
			System.out.println("Key => "+k +" value =>"+contents.get(k));
		});
		
		List data = (List) contents.get("data");
		data.forEach(d ->{
			Map matchDetail = (Map) d;
			matchDetail.forEach((k,v) ->{
				System.out.println("Key => "+k +" value =>"+matchDetail.get(k));
			});	
		});
	}

}

Run the Junit test and you can see the below output.

Key => page value =>1
Key => per_page value =>10
Key => total value =>23
Key => total_pages value =>3
Key => data value =>[[object Object], [object Object], [object Object], [object Object], [object Object], [object Object], [object Object], [object Object], [object Object], [object Object]]
Key => competition value =>UEFA Champions League
Key => year value =>2014
Key => round value =>GroupG
Key => team1 value =>Chelsea
Key => team2 value =>Schalke 04
Key => team1goals value =>1
Key => team2goals value =>1
Key => competition value =>UEFA Champions League
Key => year value =>2014
Key => round value =>GroupG
Key => team1 value =>Chelsea
Key => team2 value =>NK Maribor
Key => team1goals value =>6
Key => team2goals value =>0
Key => competition value =>UEFA Champions League
Key => year value =>2014
Key => round value =>GroupG
Key => team1 value =>Chelsea
Key => team2 value =>Sporting CP
Key => team1goals value =>3
Key => team2goals value =>1
Key => competition value =>UEFA Champions League
Key => year value =>2014
Key => round value =>R16
Key => team1 value =>Chelsea
Key => team2 value =>Paris Saint-Germain
Key => team1goals value =>1
Key => team2goals value =>1
Key => competition value =>English Premier League
Key => year value =>2014
Key => round value =>
Key => team1 value =>Chelsea
Key => team2 value =>Leicester City
Key => team1goals value =>2
Key => team2goals value =>0
Key => competition value =>English Premier League
Key => year value =>2014
Key => round value =>
Key => team1 value =>Chelsea
Key => team2 value =>Swansea City
Key => team1goals value =>4
Key => team2goals value =>2
Key => competition value =>English Premier League
Key => year value =>2014
Key => round value =>
Key => team1 value =>Chelsea
Key => team2 value =>Aston Villa
Key => team1goals value =>3
Key => team2goals value =>0
Key => competition value =>English Premier League
Key => year value =>2014
Key => round value =>
Key => team1 value =>Chelsea
Key => team2 value =>Arsenal
Key => team1goals value =>2
Key => team2goals value =>0
Key => competition value =>English Premier League
Key => year value =>2014
Key => round value =>
Key => team1 value =>Chelsea
Key => team2 value =>Queens Park Rangers
Key => team1goals value =>2
Key => team2goals value =>1
Key => competition value =>English Premier League
Key => year value =>2014
Key => round value =>
Key => team1 value =>Chelsea
Key => team2 value =>West Bromwich Albion
Key => team1goals value =>2
Key => team2goals value =>0

You can also read about JSON Schema and How to use Jackson databind with JSON

For more information, you can refer to the official Nashorn extensions documentation.

Happy Learning !!

Understanding JSON Schema

Understanding JSON Schema

JSON schema

JSON Schema is a vocabulary that allows you to annotate and validate JSON documents. It is a powerful tool for validating the structure of JSON data.

If you’ve ever used XML Schema you probably already know what a schema is, but If all that sounds unfamiliar to you, you are at the right place. To define what JSON Schema is, we should probably first learn what JSON is?

JSON stands for “JavaScript Object Notation”, a simple data interchange format. It began as a notation for the worldwide web. Since JavaScript exists in most web browsers, and JSON is based on JavaScript, it’s very easy to support there. However, it has proven useful and simple enough that it is now used in many other contexts that don’t involve web surfing.

For more detail read JSON.

Since JSON Schema is itself a JSON, it’s not always easy to tell when something is JSON Schema or just an arbitrary chunk of JSON. The $schema keyword is used to declare that something is JSON Schema. It’s generally good practice to include it, though it is not required.

{ “$schema”: “http://json-schema.org/schema#” }

Let’s try to understand the following JSON schema declaring a property name.

 
"name" : {
      "type" : "string",
      "description" : "person name"
   }

As you can see here we have JSON property “name” of type String which basically will be used to hold the person name.

So far we have understood why we need JSON schema. Now let’s dive deep into JSON Schema.

Type-specific keyword:

The type keyword is fundamental to JSON Schema. It specifies the data type for a JSON property.

Let’s look into type in more detail with attributes like length, regular expression, and format as well.

String

String:

The string type is used for textual data. It can also contain Unicode characters.

{ "type": "string" }

The following are the valid string.

“This is a string”
“Déjà vu”
“”
“63”

Length: The length of a string can be constrained using the minLength and maxLength keywords. For both keywords, the value must be a non-negative number.

{
  "type": "string",
  "minLength": 2,
  "maxLength": 3
}

Regular Expressions: The pattern keyword is used to restrict a string to a particular regular expression.

Format: The format keyword allows for basic semantic validation on string values that are commonly used. This allows values to be constrained beyond what the other tools in JSON Schema, including Regular Expressions, can do.

{
"format":"date-time"
}

Numeric Types

Numeric type:

There are two numeric types in JSON Schema: integer and number. They share the same validation keywords.

integer: The integer type is used for integral numbers.

{ "type": "integer" }

Example of a valid integer.

45
-1

number: The number type is used for any numeric type, either integers or floating-point numbers.

{ "type": "number" }

The following are the sample valid number.
42
-1
Simple floating-point number:

5.0
The exponential notation also works:
2.99792458e8

Note: Numbers as strings are rejected. For example “42” as numeric will be rejected.

multipleOf: Numbers can be restricted to a multiple of a given number, using the multipleOf keyword. It may be set to any positive number.

{
    "type"       : "number",
    "multipleOf" : 10
}

The following are the valid sample values but 23 will be rejected as it is not a valid 10 multiple.

0
10
20

Range: Ranges of numbers are specified using a combination of the minimum and maximum keywords.

{
      "type" : "integer",
      "maximum" : 10000,
      "minimum" : 1
    }

Object

Object

Objects are key-value pairs in JSON, they define mapping type and map keys to values. In JSON, the keys must always be a string. Each of these pairs is conventionally referred to as a property of the given JSON object.

{ "type": "object" }

// Sample valid JSON Objects

// Example 1
{
   "key1"  "value 1",
   "key2" : "value 2"
}

// Example 2
[
 { 
    "name"  : "user 1",
    "email" : "user1@email.com",
    "age"   : 19 
 },
 { 
    "name"  : "user 2",
    "email" : "user2@email.com",
    "age"   : 29 
 }
]

// Sample invalid JSON Objects

// Example 1
{
    0.01 : "cm"
    1    : "m",
    1000 : "km"
}

// Example 2
["An", "array", "not", "an", "object"]

Properties: The properties (key-value pairs) on an object are defined using the properties keyword. The value of properties in an object, where each key is the name of a property, and each value is a JSON schema used to validate that property.

For example, let’s say we want to define a JSON schema for an address made up of a street no, street name, and street type:

{
  "type": "object",
  "properties": {
    "street_no":   { "type": "number" },
    "street_name": { "type": "string" },
    "street_type": { "type": "string",
                     "enum": ["Street", "Avenue", "Boulevard"]
                   }
  }
}

Now if we provide the following JSON it will be validated successfully.

{ “street_no”: 1600, “street_name”: “street name 1”, “street_type”: “Avenue” }

However, if we provided the following JSON it will fail during validation.

{ “street_no”: “1600”, “street_name”: “street name 1”, “street_type”: “Avenue” }

Here we are providing street_no in a string that will be rejected by JSON schema as it is expecting a number without quotes.

In addition to that, leaving out JSON properties is valid until we marked them as required.

Required Properties: By default, the properties defined by the properties keyword are not required. However, one can provide a list of required properties using the required keyword. Refer to the below JSON schema, it has four properties out of which only two properties are marked as required.

{
  "type": "object",
  "properties": {
    "name":      { "type": "string" },
    "email":     { "type": "string" },
    "address":   { "type": "string" },
    "phone":     { "type": "string" }
  },
  "required": ["name", "email"]
}

Let see the valid JSON sample for this schema.

 
// 1 
{
  "name": "tonny",
  "email": "tonny@someemail.com"
}

// 2 

  "name": "tonny",
  "email": "tonny@someemail.com",
  "address": "tonny aaddress, city, state, country",
  "phone": "XXXXXXXXXXXX"
}

But if we provide a JSON that misses name or email or both will be rejected by the JSON schema defined above. For example, refer to the below JSON sample.

 
{
  "name": "tonny",
   "address": "tonny aaddress, city, state, country",
   "phone": "XXXXXXXXXXXX"
}

The required keyword takes an array of zero or more strings. Each of these strings must be unique.

Size: The number of properties on an object can be restricted using the minProperties and maxProperties keywords. Each of these must be a non-negative integer. Refer to the below sample JSON Schema.

{
  "type": "object",
  "minProperties": 2,
  "maxProperties": 3
}

Array

Arrays: Arrays are used for ordered elements. In JSON, each element in an array may be of a different type.

{ "type": "array" }

// Sample valid JSON array
[1, 2, 3, 4, 5]

[3, "different", { "types" : "of values" }]

// Sample invalid JSON array

{"Not": "an array"}

Items: By default, the elements of the array may be anything at all. However, it’s often useful to validate the items of the array against some schema as well. This is done using the items, additionalItems, and contains keywords.

There are two ways in which arrays are generally used in JSON:

List validation: a sequence of arbitrary length where each item matches the same schema.

Tuple validation: a sequence of fixed length where each item may have a different schema. In this usage, the index (or location) of each item is meaningful as to how the value is interpreted.

List validation: List validation is useful for arrays of arbitrary length where each item matches the same schema. For this kind of array, set the items keyword to a single schema that will be used to validate all of the items in the array. When an item is a single schema, the additionalitems keyword is meaningless, and it should not be used.

Consider the following JSON schema, where we define that each item in an array is a number:

{
  "type": "array",
  "items": {
    "type": "number"
  }
}

Array [1, 2, 3, 4, 5] will be validated successfully for above schema, however, [1, 2, “3”, 4, 5] will be failed during validation, because it has one element as string.

Note: The empty array ([]) is always valid.

Length: The length of the array can be specified using the minItems and maxItems keywords. The value of each keyword must be a non-negative number. These keywords work whether doing List validation or Tuple validation.

{
  "type": "array",
  "minItems": 2,
  "maxItems": 3
}

Refer the above JSON schema, according to this let see the valid and invalid JSON array.

[] invalid, as it an empty array
[1] invalid, only have one element
[1, 2] valid
[1, 2, 3] valid
[1, 2, 3, 4] invalid, have more than element

Uniqueness: we can even use the JSON array to accept unique items. Simply set the unique items keyword to true.

{
  "type": "array",
  "uniqueItems": true
}

[1, 2, 3, 4, 5] valid
[1, 2, 3, 3, 4] invalid
[] The empty array always passes:

boolean: The boolean type matches only two special values: true and false. Note that values that evaluate to true or false, such as 1 and 0, are not accepted by the schema.

{ "type": "boolean" }

true, valid
false, valid
“true”, invalid
Values that evaluate to true or false are still not accepted by the schema:
0, invalid
1, invalid

null: The null type is generally used to represent a missing value. But when a schema specifies a type of null, it has only one acceptable value: null.

{ "type": "null" }

null, valid
false, invalid
0, invalid
“”, invalid

I have also created a JSON schema example using Java. Get the complete code from Github https://github.com/Kuldeep-Rana/JSON_WITH_SCHEMA.git.

Reference:

json-schema.org

Happy Learning !!

How to use Jackson databind with JSON

As the use and acceptance of JSON increases, the library to work with JSON also developed. One of the most popular and efficient java based libraries to serialize or map java objects to JSON and vice versa is Jackson. In this post, I will explain how to use the Jackson databind with JSON.

JSON & Jackson

Prerequisite

  • Java 1.8
  • jackson-databind.2.9.5

Jackson Maven dependency

<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-databind</artifactId>
	<version>2.9.5</version>
</dependency>

You can copy it from the maven repository as well.

In this tutorial I will demonstrate the following:

First create three entity classes Order, Customer, and Item, I will be using them throughout the examples.

Order:

public class Order {

	private String extOrderId;
	
	private double orderAmt;
	
	private String orderDate;

	private Item item;
	
	private Customer customer;
	
        public Order() {
		super();
	}
	public Order(String extOrderId, double orderAmt, String orderDate,Item item,Customer customer) {
		super();
		this.extOrderId = extOrderId;
		this.orderAmt = orderAmt;
		this.orderDate = orderDate;
		this.item = item;
		this.customer = customer;
	}

      // Getter and Setter 
}

Customer:

public class Customer {

	private String customerName;
	
	private String mobile; 
	
	private String email;
	
        public Customer() {
		super();
	}

	public Customer(String customerName, String mobile, String email) {
		super();
		this.customerName = customerName;
		this.mobile = mobile;
		this.email = email;
	}

	public String getCustomerName() {
		return customerName;
	}
    // Getter and Setter
}

Item:

public class Item {

	private String itemName;
	
	private String manufacturer;
	
	private double price;
	
	private boolean fragile;
        
        public Item() {
		super();
	}
	public Item(String itemName, String manufacturer, double price, boolean fragile) {
		super();
		this.itemName = itemName;
		this.manufacturer = manufacturer;
		this.price = price;
		this.fragile = fragile;
	}
   // Getter and Setter
}

How to convert a Java object into JSON?

While using JSON with Java there will be a time when we have to share or write an object in the form of JSON. We can write JSON from java object by ourselves self but that would be very time-consuming. There are several libraries available to achieve these things. Let’s see how we can use Jackson data-bind to convert a Java object into JSON.

import com.codersdesks.jsondemo.bean.Customer;
import com.codersdesks.jsondemo.bean.Item;
import com.codersdesks.jsondemo.bean.Order;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class App {

	public static void main(String[] args) throws JsonProcessingException {
		ObjectMapper mapper = new ObjectMapper();
		
		Item item = new Item("Sports shoes", "Adidas", 3999.99, false);
		Customer customer = new Customer("Player 1", "##########", "email@email.net");
		
		Order order = new Order("ORDER001",2000.22,"10-09-2019",item,customer);
		
		String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(order);
		
		System.out.println(json);
	}
}

When you run the above codes snippet it will print JOSN like below.

{
  "extOrderId" : "ORDER001",
  "orderAmt" : 2000.22,
  "orderDate" : "10-09-2019",
  "item" : {
    "itemName" : "Sports shoes",
    "manufacturer" : "Adidas",
    "price" : 3999.99,
    "fragile" : false
  },
  "customer" : {
    "customerName" : "Player 1",
    "mobile" : "##########",
    "email" : "email@email.net"
  }
}

How to parse JSON to Java object?

As discussed earlier we can use the same library to parse a JSON String into a Java object. Observe the below code snippet.

import java.io.IOException;
import com.codersdesks.jsondemo.bean.Order;
import com.fasterxml.jackson.databind.ObjectMapper;

public class App {

	public static void main(String[] args) throws IOException {
		ObjectMapper mapper = new ObjectMapper();
		String json = "{\"extOrderId\":\"ORDER001\",\"orderAmt\":2000.22,\"orderDate\":\"10-09-2019\"}";
		
		Order order = mapper.readValue(json, Order.class);
		System.out.println("order "+ order);
	}
}

After executing the above code snippet the output will be:

order Order [extOrderId=ORDER001, orderAmt=2000.22, orderDate=10-09-2019, 
item=null, customer=null]

How to parse JSON into List?

Till now we have worked with a single Java object, but sometimes we may have to parse JSON into a List. Let see how it can be achieved. Here we have a JSON with multiple orders like below.

[{
	"extOrderId": "ORDER001",
	"orderAmt": 2000.22,
	"orderDate": "10-09-2019",
	"item": {
		"itemName": "Sports shoes",
		"manufacturer": "Adidas",
		"price": 3999.99,
		"fragile": false
	},
	"customer": {
		"customerName": "Player 1",
		"mobile": "##########",
		"email": "email@email.net" 

	}
}, {
	"extOrderId": "ORDER002",
	"orderAmt": 3099.99,
	"orderDate": "05-09-2019",
	"item": {
		"itemName": "Sports shoes",
		"manufacturer": "Adidas",
		"price": 3999.99,
		"fragile": false
	},
	"customer": {
		"customerName": "Player 1",
		"mobile": "##########",
		"email": "email@email.net"
	}
}]
import java.io.IOException;
import java.util.List;
import com.codersdesks.jsondemo.bean.Order;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

public class App {

	public static void main(String[] args) throws IOException {
		ObjectMapper mapper = new ObjectMapper();
		String json = "[{\"extOrderId\":\"ORDER001\",\"orderAmt\":2000.22,\"orderDate\":\"10-09-2019\",\"item\":"
				+ "{\"itemName\":\"Sports shoes\",\"manufacturer\":\"Adidas\",\"price\":3999.99,\"fragile\":false},"
				+ "\"customer\":{\"customerName\":\"Player 1\",\"mobile\":\"##########\",\"email\":\"email@email.net\"}}"
				+ ",{\"extOrderId\":\"ORDER002\",\"orderAmt\":3099.99,\"orderDate\":\"05-09-2019\",\"item\":{\"itemName\":"
				+ "\"Sports shoes\",\"manufacturer\":\"Adidas\",\"price\":3999.99,\"fragile\":false},\"customer\":"
				+ "{\"customerName\":\"Player 1\",\"mobile\":\"##########\",\"email\":\"email@email.net\"}}]";
		
		List<Order> orders = mapper.readValue(json, new TypeReference<List<Order>>() { });
		
		System.out.println(orders);
	}
}

Once you run the above code it will print:

[Order [extOrderId=ORDER001, orderAmt=2000.22, orderDate=10-09-2019,
item=Item [itemName=Sports shoes, manufacturer=Adidas, price=3999.99, fragile=false],
customer=Customer [customerName=Player 1, mobile=##########, email=email@email.net]
],
Order [extOrderId=ORDER002, orderAmt=3099.99, orderDate=05-09-2019,
item=Item [itemName=Sports shoes, manufacturer=Adidas, price=3999.99, fragile=false],
customer=Customer [customerName=Player 1, mobile=##########, email=email@email.net]
]]

How to parse JSON into Map?

Similar to Converting JSON into a Java object or converting JSON into a list we can convert JSON into a Map as well. Observe the below code snippet.

import java.io.IOException;
import java.util.Map;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

public class App {

	public static void main(String[] args) throws IOException {
		ObjectMapper mapper = new ObjectMapper();
		String json = "{\"extOrderId\":\"ORDER001\",\"orderAmt\":2000.22,\"orderDate\":\"10-09-2019\"}";
		
		Map<String, String> map = mapper.readValue(json, new TypeReference<Map<String, String>>() {});
		
		System.out.println(map);
	}
}

Once you run the code snippet it will print:

{extOrderId=ORDER001, orderAmt=2000.22, orderDate=10-09-2019}

How to ignore object property?

Enough of parsing JSON into an object and converting an object into JSON. Apart from this requirement while working on a real-world application sometimes you may face a situation where you have an existing class, which needs to be converted into JSON, but you have to omit some properties while writing the JSON.

For example, you have a User class like below, where you have to share the details of a user in the form JSON. But the User class also has a property password that holds the password of the user. In any case, you don’t want to share the user details with a password. In such cases, you can use @JsonIgnore annotation provided by Jackson data bind.

import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonIgnore;

public class User implements Serializable{

	private static final long serialVersionUID = -1686914925084201531L;

	private int id;
	private String name;
	private String email;
	
	@JsonIgnore
	private String password;
	
	public User() {
		super();
	}
	
	public User(int id, String name, String email, String password) {
		super();
		this.id = id;
		this.name = name;
		this.email = email;
		this.password = password;
	}
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", email=" + email + ", password=" + password + "]";
	}
	
}

Let’s create an object of User class and write it as JSON. Observer the following code snippet with its output.

import java.io.IOException;
import com.codersdesks.jsondemo.bean.User;
import com.fasterxml.jackson.databind.ObjectMapper;

public class App {

	public static void main(String[] args) throws IOException {
		ObjectMapper mapper = new ObjectMapper();
		User user = new User(1, "User 1", "user1@email.net", "password");
		System.out.println(mapper.writeValueAsString(user));
	}
}

When you run the above code snippet it will print the JSON of the User as below after omitting the password property in JSON.

{"id":1,"name":"User 1","email":"user1@email.net"}

Recommended Read:

What is JavaScript Object Notation (JOSN)

Happy Learning !!

What is JavaScript Object Notation (JOSN)

In This tutorial we will learn, what are JavaScript Object Notation (JSON), JSON data type, and the characteristics of JSON.

What is JSON?

JavaScript Object Notation (JSON)

JavaScript Object Notation (JSON) is an open-standard file format that uses human-readable text to transmit data objects. It is a language-independent data format consisting of attribute-value pairs and array data types (or any other serializable value). It is a very common data format, with a diverse range of applications, such as serving as the replacement for XML and the response of AJAX systems.

It was derived from JavaScript, but as the use of JSON increases many programming languages developed code to generate and parse JSON-format data. The official media type for JSON is application/json. JSON filenames use the extension .json.

A sample JSON will look like as below.

{
	"name": "Smith",
	"age": "34",
	"email": "smith@somedomain.com",
	"mobile": "1234567890"
}

Uses of JSON:

  • JSON is used while developing JS-based applications that include browser extensions and websites.
  • The JSON format is used for serializing and transmitting structured data over the network connection.
  • JSON is primarily used to transmit data between a server and web applications.
  • Web services and APIs use JSON format to provide exchange data.
  • JSON can be used with modern programming languages.

Characteristics of JSON:

  • JSON is easy to read and write.
  • It is a lightweight text-based interchange format.
  • JSON is language independent.
  • Easy conversion to and from an object.

Data types and syntax:

Data TypeDescription
NumberA signed decimal number that may contain a fractional part and may use exponential E notation, but cannot include non-numbers such as NaN. The format makes no distinction between integer and floating-point. JavaScript uses a double-precision floating-point format for all its numeric values, but other languages implementing JSON may encode numbers differently.
StringA sequence of zero or more Unicode characters. Strings are delimited with double-quotation marks and support a backslash escaping syntax.
BooleanEither of the values true or false
ArrayAn ordered list of zero or more values, each of which may be of any type. Arrays use square bracket notation with comma-separated elements.
ObjectAn unordered collection of name–value pairs where the names (also called keys) are strings. Objects are intended to represent associative arrays, where each key is unique within an object.

Objects are delimited with curly brackets and use commas to separate each pair, while within each pair the colon ':' character separates the key or name from its value.
null An empty value, using the word null

Whitespace is allowed and ignored around or between syntactic elements (values and punctuation, but not within a string value). Four specific characters are considered whitespace for this purpose: space, horizontal tab, line feed, and carriage return. In particular, the byte order mark must not be generated by a conforming implementation (though it may be accepted when parsing JSON). JSON does not provide syntax for comments.

Early versions of JSON (such as specified by RFC 4627) required that a valid JSON text must consist of only an object or an array type, which could contain other types within them.

Sample JSON: Let’s create some sample JSON of different types.

Creating Simple Object: A simple object can have a single or multiple key-value pairs separated with comma(,) of any of the data type defined in the above table. An object in JSON starts with an opening curly bracket “{” and end with closing curly bracket “}”.

{
	"extOrderId": "ORDER001",
	"orderAmt": 2000.22,
	"orderDate": "10-09-2019"
}

An Object with an Object: Similar to the above single object, one object can contain one or multiple object references.

(A) Single object reference.

{
	"extOrderId": "ORDER001",
	"orderAmt": 2000.22,
	"orderDate": "10-09-2019",
	"item": {
		"itemName": "Sports shoes",
		"manufacturer": "Adidas",
		"price": 3999.99,
		"fragile": false
	}
}

(B) Multiple objects reference.

{
	"extOrderId": "ORDER001",
	"orderAmt": 2000.22,
	"orderDate": "10-09-2019",
	"item": {
		"itemName": "Sports shoes",
		"manufacturer": "Adidas",
		"price": 3999.99,
		"fragile": false
	},
	"customer": {
		"customerName": "Bolt",
		"mobile": "##########",
		"email": "email@email.net"
	}
}

Object Array: A JSON array consists of multiple objects similar to an array in any programming language. An array starts with an opening square bracket “[” and end with closing square bracket “]”.

[{
	"extOrderId": "ORDER001",
	"orderAmt": 2000.22,
	"orderDate": "10-09-2019",
	"item": {
		"itemName": "Sports shoes",
		"manufacturer": "Adidas",
		"price": 3999.99,
		"fragile": false
	},
	"customer": {
		"customerName": "Bolt",
		"mobile": "##########",
		"email": "email@email.net"
	}
}, {
	"extOrderId": "ORDER002",
	"orderAmt": 3099.99,
	"orderDate": "05-09-2019",
	"item": {
		"itemName": "Sports shoes",
		"manufacturer": "Adidas",
		"price": 3999.99,
		"fragile": false
	},
	"customer": {
		"customerName": "Bolt",
		"mobile": "##########",
		"email": "email@email.net"
	}
}]

Reference:

https://json.org/

https://en.wikipedia.org/wiki/JSON

Happy Learning !!