Tuesday, 30 March 2021

jsonschema2pojo-core tutorial: Generate pojos from json

‘jsonschema2pojo-core’ library is used to generate POJOs from json and json schema documents.

 

I am using following dependency throughout this tutorial.

<dependency>
	<groupId>org.jsonschema2pojo</groupId>
	<artifactId>jsonschema2pojo-core</artifactId>
	<version>1.1.0</version>
</dependency>

 


      Generate POJOs from json document
      Generate POJOs from json schema

 

Previous                                                    Next                                                    Home

Php: Constants

Constants are used to define immutable variables. Suppose if you have aa scenario such that where the value of variable shouldn’t change throughout application life cycle, you should define that variable as constant.

 

How to define a constant variable?

Constants are defined using ‘define’ function.

 

Example

define("__PI__", 3.14);

 

__PI__ is the name of the constant and it has value 3.14.

 

Constant naming conventions

a.   Constant name must starts with a letter or underscore, followed by any number of letters, numbers or underscores with one exception.

b.   By convention, constant variable name is always uppercase.

 

constant_demo.php

#!/usr/bin/php

<?php
    
   define("__PI__", 3.14);
   
   echo __PI__;
?>

Output

$./constant_demo.php 

3.14


Note

$ prefix is not required for constant names.



 

  

Previous                                                    Next                                                    Home

Bean validation: Email: validate email

If you annotate @Email annotation on top of CharSequence, then the CharSequence should be a well-formed email address.

 

Example

@Email

public String emailId;

 

What are the supported types?

You can apply this annotation on any CharSequence type.

 

Where can I apply this annotation?

a.   METHOD, F

b.   IELD,

c.    ANNOTATION_TYPE,

d.   CONSTRUCTOR,

e.   PARAMETER,

f.     TYPE_USE

 

Find the below working application.

 

Employee.java

package com.sample.model;

import javax.validation.constraints.Email;

public class Employee {

	private int id;

	private String name;

	@Email
	public String emailId;

	public Employee(int id, String name, String emailId) {
		this.id = id;
		this.name = name;
		this.emailId = emailId;
	}

	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 getEmailId() {
		return emailId;
	}

	public void setEmailId(String emailId) {
		this.emailId = emailId;
	}

}

 

Test.java

package com.sample.test;

import java.util.Set;

import javax.validation.*;
import javax.validation.ValidatorFactory;

import com.sample.model.Employee;

public class Test {
	private static ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
	private static Validator validator = validatorFactory.getValidator();

	private static void validateBean(Employee emp) {
		System.out.println("************************************");
		Set<ConstraintViolation<Employee>> validationErrors = validator.validate(emp);

		if (validationErrors.size() == 0) {
			System.out.println("No validation errors....");
		}

		for (ConstraintViolation<Employee> violation : validationErrors) {
			System.out.println(violation.getPropertyPath() + "," + violation.getMessage());
		}
		System.out.println("");
	}

	public static void main(String args[]) {

		Employee emp1 = new Employee(1, "Krishna", "AA");
		System.out.println("Validation errors on bean emp1");
		validateBean(emp1);

		Employee emp2 = new Employee(2, "Siva", "krihsna@abc.com");
		System.out.println("Validation errors on bean emp2");
		validateBean(emp2);
	}
}

 

Output

Validation errors on bean emp1
************************************
emailId,must be a well-formed email address

Validation errors on bean emp2
************************************
No validation errors....

 

 

 

 

  

Previous                                                    Next                                                    Home

javax.json: Generate json using JsonGenerator

 

JsonGenerator is used to generate json content and writes JSON data to an output source in a streaming way.

 

How to create a JsonGenerator?

You can create JsonGenerator by passing an output stream as argument to createGenerator method of Json class.

 

Example

ByteArrayOutputStream bos = new ByteArrayOutputStream();

JsonGenerator jsonGenerator = Json.createGenerator(bos);

 

How to generate json content?

‘JsonGenerator’ class provides multiple write* method to write json content.

 

jsonGenerator.writeStartObject();

Writes json start object character.

 

jsonGenerator.writeStartArray("hobbies");

Writes the JSON name/start array character pair with in the current object context.

 

jsonGenerator.writeEnd();

Writes the end of the current context. If the current context is an array context, this method writes the end-of-array character (']'). If the current context is an object context, this method writes the end-of-object character ('}').

 

Find the below working application.

 

JsonGeneratorDemo.java

package com.sample.app;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.json.Json;
import javax.json.stream.JsonGenerator;

public class JsonGeneratorDemo {
        public static void main(String args[]) throws IOException {
                try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {

                        try (JsonGenerator jsonGenerator = Json.createGenerator(bos);) {

                                jsonGenerator.writeStartObject();

                                jsonGenerator.write("id", 123);
                                jsonGenerator.write("name", "Krishna");

                                // Write nested json document
                                jsonGenerator.writeStartObject("address").write("street", "Chodeswari").write("city", "Bangalore")
                                                .writeEnd();

                                // Write array content
                                jsonGenerator.writeStartArray("hobbies");
                                jsonGenerator.write("Cricket");
                                jsonGenerator.write("Chess");
                                jsonGenerator.writeEnd();

                                jsonGenerator.writeEnd();

                        }

                        String finalString = new String(bos.toByteArray());

                        System.out.println(finalString);

                }

        }

}

 

Output

{"id":123,"name":"Krishna","address":{"street":"Chodeswari","city":"Bangalore"},"hobbies":["Cricket","Chess"]}

 

 

 

 

Previous                                                    Next                                                    Home

javax.json: Write json string to a file

Step 1: Create an output stream to a file.

OutputStream os = new FileOutputStream(FILE_TO_WRITE);

 

Step 2: Create a JsonWriter instance.

JsonWriter jsonWriter = Json.createWriter(os);

 

Step 3: Write the json object to the file using writer.

jsonWriter.writeObject(jsonObject);

 

Find the below working application.

 

WriteToFileDemo.java

package com.sample.app;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringReader;

import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.json.JsonWriter;

public class WriteToFileDemo {
        public static void main(String[] args) throws IOException {
                final String JSON_STRING = "{\n" + 
                                "    \"firstName\": \"Ram\",\n" + 
                                "    \"lastName\": \"Gurram\",\n" + 
                                "    \"id\": 32,\n" + 
                                "    \"male\": false,\n" + 
                                "    \"dateOfBirth\": \"10/01/1985\"\n" + 
                                "}\n";
                
                final String FILE_TO_WRITE = "/Users/Shared/json/emp.json";
                
                try (JsonReader reader = Json.createReader(new StringReader(JSON_STRING));
                                OutputStream os = new FileOutputStream(FILE_TO_WRITE);
                                JsonWriter jsonWriter = Json.createWriter(os);) {
                        
                        JsonObject jsonObject = reader.readObject();

                        jsonWriter.writeObject(jsonObject);
                }

        }

}

Run above application and open the file ‘/Users/Shared/json/emp.json’ to confirm the json content.

$ cat /Users/Shared/json/emp.json 
{"firstName":"Ram","lastName":"Gurram","id":32,"male":false,"dateOfBirth":"10/01/1985"}




 

 

Previous                                                    Next                                                    Home

javax.json: Read json from a file

Step 1: Create input stream for the file.

InputStream fis = ReadFromFileDemo.class.getClassLoader().getResourceAsStream(JSON_FILE);

 

Step 2: Get JsonReader instance from the inputstream.

JsonReader jsonReader = Json.createReader(fis)

 

Step 3: Get JsonObject from readObject method of JsonReader

JsonObject jsonObject = jsonReader.readObject();

 

Find the below working application.

 

ReadFromFileDemo.java

package com.sample.app;

import java.io.IOException;
import java.io.InputStream;

import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;

public class ReadFromFileDemo {
        public static final String JSON_FILE = "employee.json";

        public static void main(String[] args) throws IOException {

                try (InputStream fis = ReadFromFileDemo.class.getClassLoader().getResourceAsStream(JSON_FILE);
                                JsonReader jsonReader = Json.createReader(fis)) {

                        JsonObject jsonObject = jsonReader.readObject();

                        String result = jsonObject.toString();
                        System.out.println(result);

                }

        }
}

 

Output

{"firstName":"Ram","lastName":"Gurram","id":32,"male":false,"dateOfBirth":"10/01/1985"}

 

 

 

  

Previous                                                    Next                                                    Home

Javax.json: Query json using streaming api

 

The Streaming API of JSON-P supports parsing a JSON string. Streaming API is more effective and preferrable method to parse big json documents. Streaming API provides JsonParser class which provides extremely fast, read-only, forward access to json documents.

 

JsonParser.Event enum provides following constants to identify the events in parsing state.

 

Constant

Description

START_ARRAY

Represent the start of a json array

START_OBJECT

Start of a JSON object. The position of the parser is after '{'.

KEY_NAME

Name in a name/value pair of a JSON object. The position of the parser is after the key name. The method getString returns the key name.

VALUE_STRING

String value in a JSON array or object. The position of the parser is after the string value. The method getString returns the string value.

VALUE_NUMBER

Number value in a JSON array or object. The position of the parser is after the number value. JsonParser provides the following methods to access the number value: getInt, getLong, and getBigDecimal.

VALUE_TRUE

true value in a JSON array or object. The position of the parser is after the true value.

VALUE_FALSE

false value in a JSON array or object. The position of the parser is after the false value.

VALUE_NULL

null value in a JSON array or object. The position of the parser is after the null value.

END_OBJECT

End of a JSON object. The position of the parser is after '}'.

END_ARRAY

End of a JSON array. The position of the parser is after ']'.

 

How to create a parser from json string?

'Json.createParser' method is used to create a parser.

 

Example

JsonParser parser = Json.createParser(new StringReader(jsonString));

 

Once you got the JsonParser instance, you can use hasNext() and next() methods to parse the json string.

 

Example

while(parser.hasNext()){
   final Event event = parser.next();
   switch(event){
      ......
   }
}

 

Find the below working application.

 

JsonParserDemo.java

package com.sample.app;

import java.io.StringReader;
import java.math.BigDecimal;

import javax.json.Json;
import javax.json.stream.JsonParser;
import javax.json.stream.JsonParser.Event;

public class JsonParserDemo {

        public static void main(String[] args) {

                String jsonString = "{\n" + "  \"id\": 1,\n" + "  \"firstName\": \"Ram\",\n" + "  \"lastName\": \"Gurram\"\n"
                                + "}";

                JsonParser parser = Json.createParser(new StringReader(jsonString));
                String key = null;
                while (parser.hasNext()) {
                        final Event event = parser.next();
                        switch (event) {
                        case KEY_NAME:
                                key = parser.getString();
                                System.out.print(key);
                                break;
                        case VALUE_STRING:
                                String string = parser.getString();
                                System.out.println(" -> " + string);
                                break;
                        case VALUE_NUMBER:
                                BigDecimal number = parser.getBigDecimal();
                                System.out.println(" -> " + number);
                                break;
                        case VALUE_TRUE:
                                System.out.print(true);
                                break;
                        case VALUE_FALSE:
                                System.out.print(false);
                                break;
                        case START_ARRAY:
                                System.out.println("[");
                                break;
                        case END_ARRAY:
                                System.out.println("]");
                                break;
                        case START_OBJECT:
                                break;
                        case VALUE_NULL:
                                System.out.print("null");
                                break;
                        case END_OBJECT:
                                System.out.println();
                                break;
                        default:
                                break;
                        }
                }
                parser.close();
        }

}

 

Output

id -> 1
firstName -> Ram
lastName -> Gurram

 

 

 

 

Previous                                                    Next                                                    Home