Category Archives: Uncategorized

JAVA : How to convert YAML Documents to JSON List?

Here is code to convert YAML documents to JSON objects by Jackson and snakeyml apis. Jackson also support YAML support.

Pre-Requisite



        <dependencies>
        <!-- Jackson JSON Processor -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.4.1</version>
        </dependency>
        <!-- For YAML -->
        <dependency>
            <groupId>org.yaml</groupId>
            <artifactId>snakeyaml</artifactId>
            <version>1.21</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-yaml</artifactId>
            <version>2.1.2</version>
        </dependency>
    </dependencies>   

Sample YAML Documents File


---
# My personal record
name: Saurabh Kumar Gupta
Title: Sr. Project Lead
skill: JAVA/J2EE
employed: True
domains:
    - Telecom
    - Finance
    - Banking
    - Healthcare
languages:
    ELK: Medium
    JAVA: Expertize
    Scripting: Comfortable
education: |
    MCA
    B.Sc
    Diploma

---
# Gaurav personal record
name: Gaurav Gupta
Title: Project Lead
skill: ELK
employed: True
domains:
    - Telecom
    - Banking
    - Healthcare
languages:
    ELK: Medium
    JAVA: Expertize
    Scripting: Comfortable
    Bigdata: Expertize
education: |
    MCA
    B.Sc

Code to Convert YAML documents to JSON Objects

package com.fiot.examples.yaml;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Iterator;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;

public class ConvertYAMLObjectsToJSON {
	public static void main(String[] args) {
		try (InputStream input = new FileInputStream(new File(
				"F:\\Workspace-Blog\\TestExamples\\src\\main\\resources\\YAMLDocument2.yaml"))) {
			Yaml yaml = new Yaml(new SafeConstructor());
			Iterator iterator = yaml.loadAll(input).iterator();
			while (iterator.hasNext()) {
				System.out.println(iterator.next());
			}
		} catch (Throwable e) {
			System.out.println("ERROR: " + e.getMessage());
		}
	}
}

Output


{name=Saurabh Kumar Gupta, Title=Sr. Project Lead, skill=JAVA/J2EE, employed=true, domains=[Telecom, Finance, Banking, Healthcare], languages={ELK=Medium, JAVA=Expertize, Scripting=Comfortable}, education=MCA
B.Sc
Diploma
}
{name=Gaurav Gupta, Title=Project Lead, skill=ELK, employed=true, domains=[Telecom, Banking, Healthcare], languages={ELK=Medium, JAVA=Expertize, Scripting=Comfortable, Bigdata=Expertize}, education=MCA
B.Sc}

More

To know more about YAML Syntax, Configuration with Java and other supporting language, frameworks and tools, Sample configuration files and JSON and YAML conversion follow below YAML Tutorials and YAML related exceptions follow YAML Issues.

Advertisements

JAVA : How to convert YAML To JSON?

Here is code to convert YAML document to JSON by Jackson and snakeyml apis. Jackson also support YAML support.

Pre-Requisite


<dependencies>
        <!-- Jackson JSON Processor -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.4.1</version>
        </dependency>
        <!-- For YAML -->
        <dependency>
            <groupId>org.yaml</groupId>
            <artifactId>snakeyaml</artifactId>
            <version>1.21</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-yaml</artifactId>
            <version>2.1.2</version>
        </dependency>
    </dependencies>

Sample YAML File


---
# My personal record
name: Saurabh Kumar Gupta
Title: Sr. Project Lead
skill: JAVA/J2EE
employed: True
domains:
    - Telecom
    - Finance
    - Banking
    - Healthcare
languages:
    ELK: Medium
    JAVA: Expertize
    Scripting: Comfortable
education: |
    MCA
    B.Sc
    Diploma
...

Code to convert YAML to JSON data

package com.fiot.examples.yaml;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;

public class ConvertYAMLToJSON {
	public static void main(String[] args) {
		String content = "";
		try {
			content = new String(Files.readAllBytes(Paths.get(
					"F:\\Workspace-Blog\\TestExamples\\src\\main\\resources\\YAMLDocument.yaml")));
			System.out.println("*********Content from YAML File ****************");
			System.out.println(content);
			String json = convertYamlToJson(content);
			System.out.println("*********Cnverted JSON from YAML File ****************");
			System.out.println(json);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static String convertYamlToJson(String yaml) {
		try {
			ObjectMapper yamlReader = new ObjectMapper(new YAMLFactory());
			Object obj = yamlReader.readValue(yaml, Object.class);
			ObjectMapper jsonWriter = new ObjectMapper();
			return jsonWriter.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
		} catch (JsonProcessingException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return null;
	}
}

Output


*********Content from YAML File ****************
---
# My personal record
name: Saurabh Kumar Gupta
Title: Sr. Project Lead
skill: JAVA/J2EE
employed: True
domains:
    - Telecom
    - Finance
    - Banking
    - Healthcare
languages:
    ELK: Medium
    JAVA: Expertize
    Scripting: Comfortable
education: |
    MCA
    B.Sc
    Diploma
...
*********Cnverted JSON from YAML File ****************
{
  "name" : "Saurabh Kumar Gupta",
  "Title" : "Sr. Project Lead",
  "skill" : "JAVA/J2EE",
  "employed" : true,
  "domains" : [ "Telecom", "Finance", "Banking", "Healthcare" ],
  "languages" : {
    "ELK" : "Medium",
    "JAVA" : "Expertize",
    "Scripting" : "Comfortable"
  },
  "education" : "MCA\nB.Sc\nDiploma\n"
}

Below are some online tools to convert YAML/YML to JSON.
https://codebeautify.org/yaml-to-json-xml-csv
http://convertjson.com/yaml-to-json.htm

More

To know more about YAML Syntax, Configuration with Java and other supporting language, frameworks and tools, Sample configuration files and JSON and YAML conversion follow below YAML Tutorials and YAML related exceptions follow YAML Issues.

Difference between YAML and JSON

 

“YAML is superset of JSON”

Below are comparison between YAML and JSON by conceptually and writing differences

YAML vs JSON

  • YAML is best suited for configuration while JSON is better as a serialization format or serving up data for your APIs.
  • YAML is by no means  a replacement for JSON .You should use the data format that makes the most sense for what you are trying to accomplish.

YAML Advantage

  • YAML has a couple of big advantages  including the ability to self reference, support for complex datatypes, embedded block literals, comments, and more.
  • Write your configuration files in YAML format where you have the opportunity – it is designed to be readable and easily editable by humans.

JSON Disadvantage

  • JSON designed to be human readable – intentionally lacking features to support editing.
  • JSON doesn’t support comments – this is intentionally left out of the JSON specification because its not what the format was designed for.

JSON vs YAML

  • JSON is well suited for  serialization format to data interchange between apis over network.
  • JSON ships with a far simpler specification than YAML.
  • JSON  learning is faster in comparison to YAML, because it is not nearly as robust in its feature set.
  • YAML is a superset of JSON, which means you can parse JSON with a YAML parser.

JSON Advantage

  • JSON is  best to data interchange.

Disadvantage of YAML

  • YAML parsers are younger and  known to be less secure.
  • YAML is mainly designed for configuration when use for data interchange , many of YAMLs features lose their appeal.

Syntax Difference between YAML and JSON

Below are some syntax difference in YAML and JSON while writing files:

JSON Syntax

  • JSON is a subset of the JavaScript object notation syntax.
  • JSON data stored in name/value pairs.
  • JSON records separated by commas.
  • JSON field names & strings are wrapped by double quotes.

YAML Syntax

  • YAML stands for ain’t markup language and is a superset of JSON – You Convert YAML to JSON
  • YAML files begin with ‘—‘, marking the start of the document.
  • YAML documents end with ‘…’ but it’s optional.
  • YAML key value pairs are separated by colon.
  • YAML lists begin with a hyphen.

More

To know more about YAML Syntax, Configuration with Java and other supporting language, frameworks and tools, Sample configuration files and JSON and YAML conversion follow below YAML Tutorials and YAML related exceptions follow YAML Issues.

 

YAML Introduction

YAML(Ain’t Markup Language) is a human friendly , cross language, unicode based data serialization format designed for interaction with all programming languages.

File Name Extension : .yml or .yaml

Latest Release : 1.2

It is broadly use for programming:

  • Configuration Files
  • Internet Messaging
  • Object Persistence to data auditing
  • Also support for Unicode standards characters.

YAML allow data to show itself in a natural and meaningful way and provide a unique cleanness by minimizing the amount of structural characters.
For example: indentation may be used for structure, colons use to separate “mapping key: value” pairs, and dashes are used to create “bullet” lists for showing collections of data.

YAML is a superset of JSON : you can convert YAML to JSON by different API’s

YAML Goals

Below are main design goals for YAML :

  • YAML is easily readable and understandable by humans.
  • YAML is expressive and extensible.
  • YAML is easy to implement and use.
  • YAML matches the native data structures of agile languages.
  • YAML data is portable between programming languages.
  • YAML has a consistent model to support generic tools.
  • YAML supports one-pass processing.

YAML Documents Processing

A YAML document is parsed only when the iterator is invoked (lazy evaluation).

More

To know more about YAML Syntax, Configuration with Java and other supporting language, frameworks and tools, Sample configuration files and JSON and YAML conversion follow below YAML Tutorials and YAML related exceptions follow YAML Issues.

 

[Solved] Maven: No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK

This maven exception occurs  when your Window/Unix environment variable for JAVA_HOME and PATH are pointing to JRE instead of JDK. That’s why maven will not compile code and throw below exception.

Problem

[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building SpringBootApp 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-install-plugin/2.5.2/maven-install-plugin-2.5.2.pom
[INFO] Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-install-plugin/2.5.2/maven-install-plugin-2.5.2.pom (7 KB at 2.3 KB/sec)
[INFO] Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-plugins/25/maven-plugins-25.pom
[INFO] Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-plugins/25/maven-plugins-25.pom (10 KB at 10.2 KB/sec)
[INFO]
[INFO] --- maven-resources-plugin:3.0.1:resources (default-resources) @ SpringBootApp ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 0 resource
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.7.0:compile (default-compile) @ SpringBootApp ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to D:\Saurabh Gupta\facingIssuesOnIT\SpringBootApp\target\classes
[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
[INFO] 1 error
[INFO] -------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 5.342 s
[INFO] Finished at: 2018-05-28T15:59:31+05:30
[INFO] Final Memory: 20M/209M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.7.0:compile (default-compile) on project SpringBootApp: Compilation failure
[ERROR] No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
[ERROR] -&gt; [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

Solutions

To resolve this issue you can follow below steps by solving command prompt or Eclipse.

Command Prompt

How to Configure Maven in Window and Linux?

Eclipse

  • Right click on project -> Select Properties
  • Select Java Build Path-> Libraries Tab -> Click on Add Library
  • Refer below link for reference.

Eclipse : How to set java path of JDK/JRE?

[Solved] java.lang.ArithmeticException: / by zero in JAVA

java.lang.ArithmeticException is Unchecked exception and sub class of java.lang.RuntimeException. It’s thrown when an exceptional condition occurred in Arithmetic Operations. It can also occurred by virtual machine as if suppression were disabled and /or the stack trace was not writable.

Constructors:

  • ArithmeticException() : Constructs an ArithmeticException with no detail message.
  • ArithmeticException(String s) : Constructs an ArithmeticException with the specified detail message.
Example :
An integer value “divide by zero” throw ArithmaticException.  In below example i am dividing int, double, float and long value with 0. For long and int type value it’s throwing Arithmatic Exception while for double and float printing special value as Infinity.  See below How to fix Arithmetic Exception? section.
package example;

public class ArithmaticExceptionExample {

	public static void main(String[] args) {
		int x=0;
		int y=5;
		double z=6;
		float l=6;
		long k=10L;
		//Integer value divide by integer value as 0 throw ArithmeticException
		try
		{
			System.out.println("Integer value divide by zero");
		System.out.println(y/x);
		}
		catch(ArithmeticException ex)
		{
			ex.printStackTrace();
		}
		//Double value divide by integer value as 0 No Exception special value Infinity
		System.out.println("Double value divide by zero");
		System.out.println(z/x);

		//Float value divide by integer value as 0 No Exception special value Infinity
		System.out.println("Float value divide by zero");
		System.out.println(l/x);

		//Long value divide by integer value as 0 throw ArithmeticException
		try
		{
		System.out.println("Long value divide by zero");
		System.out.println(k/x);
		}
		catch(ArithmeticException ex)
		{
			ex.printStackTrace();
		}

	}

}

Output:

Integer value divide by zero
java.lang.ArithmeticException: / by zero
	at example.ArithmaticExceptionExample.main(ArithmaticExceptionExample.java:15)
Double value divide by zero
Infinity
Float value divide by zero
Infinity
Long value divide by zero
java.lang.ArithmeticException: / by zero
	at example.ArithmaticExceptionExample.main(ArithmaticExceptionExample.java:31)

How to fix Arithmetic Exception?

In above example:

Y/X or K/X result ArithmeticException

What happens here is that since both the dividend and the divisor are int, the operation is an integer division, whose result is rounded to an int. Remember that an int can only contain whole number (of limited range, some 4 billion numbers approximately) That’ s why throwing Arithmatic Exception. same case for long value.

Z/X or L/X result special value Infinity

Here float (L) or double (X) precision value  divide by zero store in float and double value that why result is special value Infinity.

 

[Solved] NullPointerException In Java

NullPointerException is Runtime Exception and Unchecked Exception which thrown when trying to access an object which is having value as null.

What is Null Value?

Null value is a special  value which tell JVM this reference variable is assigned with no value as null. It means variable is not pointing to any object instances and not having any value.

Cases when NullPointerException Happen:

  • Accessing or modifying a null object’s field.
  • Taking length of null  from object like String, Array, ArrayList etc.
  • Invoking a method from a null object.
  • Calling method passing argument as wrapper object having null value while method having primitive arguments.
  • Accessing or modifying the slots of null object, as if it were an array.
  • Throwing null, as if it were a Throwable value.
  • When you try to synchronize over a null object.

Below are some examples for NullPointerException for above cases which showing how NullPointerException can happen in your code.

import java.util.List;

public class NullPointerExceptionExample {

	public static void main(String[] args) {
		//Example 1: String object assigned with null
		try
		{
		String str=null;
		if(str.length()&gt;0)//NullPointerException Here
			System.out.println("String Length :"+str.length());
		}
		catch(NullPointerException ex)
		{
			System.out.println("Example 1 :String object assigned with null");
			ex.printStackTrace();
		}

		//Example 2: Collection List Object Assigned with Null
		try
		{
		List list=null;
		if(list.size()&gt;0)//NullPointerException Here
			System.out.println("List Length :"+list.size());
		}
		catch(NullPointerException ex)
		{
			System.out.println("Example2 :Collection List object assigned with null");
			ex.printStackTrace();
		}

		//Example 3: Calling method with wrapper and method having primitive value
		try
		{
		Long acNumber=null;
		checkValue(acNumber);
		}
		catch(NullPointerException ex)
		{
			System.out.println("Example 3 :Calling method with wrapper and method having primitive type");
			ex.printStackTrace();
		}

		//Example 4 :Accessing slot of Array object having value as null
		try
		{
		Employee [] empArr=new Employee[10];
		System.out.println("Employee Name :"+empArr[5].getName());
		}
		catch(NullPointerException ex)
		{
			System.out.println("Example 4: Accessing slot of array objet having value as null");
			ex.printStackTrace();
		}
	}

	public static void checkValue(long acNumber)
	{
		System.out.println("Account Number:"+acNumber);
	}

	private class Employee
	{
		private int id;
		private String name;
		private double salary;

		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 double getSalary() {
			return salary;
		}
		public void setSalary(double salary) {
			this.salary = salary;
		}

	}

}

Output :

Example 1 :String object assigned with null
java.lang.NullPointerException
	at example.NullPointerExceptionExample.main(NullPointerExceptionExample.java:12)
Example2 :Collection List object assigned with null
java.lang.NullPointerException
	at example.NullPointerExceptionExample.main(NullPointerExceptionExample.java:25)
Example 3 :Calling method with wrapper and method having primitive type
java.lang.NullPointerException
        at
example.NullPointerExceptionExample.main(NullPointerExceptionExample.java:38)
Example 4: Accessing slot of array objet having value as null
java.lang.NullPointerException
	at example.NullPointerExceptionExample.main(NullPointerExceptionExample.java:50)

 How to avoid NullPointerException?

NullPointerException can be avoid by using considering below points:

  • Need to ensure object as initialize properly before any operation check for null .
  • Need to ensure object reference is not null before calling any method or operation on fields.
  • While comparing string with literals. Instead of invoking the method from the null object, consider invoking it from the literal.
  • Before calling method check arguments if valid then only call methods.
  • Use of Ternary operator for initialize with some default value if object value is null.
  • We can use NullPointerException catch block when no action perform or if need to throw some Customize Exception or User Defined Exception.

In below example consider all above case for avoid NullPointerException.

public class NullPointerExceptionExample {

	public static void main(String[] args) {
		//Example 1: String object assigned with null
		//NullPointerException avoided by checking null before use
		String str=null;
		if(str!=null &amp;&amp; str.length()&gt;0)
			System.out.println("String Length :"+str.length());

		//Example 2: Object assigned with Null
		//NullPointerException avoided by using  null check before accessing field
		Employee emp=null;
		if(emp!=null)
			System.out.println("Employee Name :"+emp.getName());

		//Example 3: name is assigned with null
		//NullPointerException avoided by calling equals method from literals instead of name object.
		String name=null;
		if("FacingIssuesOnIT".equals(name))
		{
			System.out.println("Name is FacingIssuesOnIT");
		}
		else
		{
			System.out.println("Name is not FacingIssuesOnIT");
		}

		//Example 4: Calling method with wrapper as null and method having primitive value
		//NullPointerException avoided by checking null on method arguments before calling method.

		Long acNumber=null;
		if(acNumber!=null)
		{
		checkValue(acNumber);
		}

		//Example 5: Object reference value is null and need to perform operation
		//NullPointerException avoided by using ternary operator
		String siteName=null;
		name=siteName==null?"":siteName;
		System.out.println("Site Name Length:"+name.length() );

	}

	public static void checkValue(long acNumber)
	{
		System.out.println("Account Number:"+acNumber);
	}

	private class Employee
	{
		private int id;
		private String name;
		private double salary;

		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 double getSalary() {
			return salary;
		}
		public void setSalary(double salary) {
			this.salary = salary;
		}

	}

}

Summary

  • Here you have learn about NullPointerException and Null value.
  • Cases with examples where NullPointerException can happen.
  • Al so explained with example to avoid NullPointerException by applying null check on object, compare String values by calling operations on literals and using ternary operators.

How to Swap two Numbers with and with out temporary variable.

Here I will show you how you can swap two numbers A=20 and B=10 with and without temporary variables as A=10 and B=20.

Swap Numbers with Temporary Variable

I will take one more temporary variable as temp to keep value of B so that during  copy of value A to B value of B is in temp and now we can copy value of temp to A. As below

temp=B       (This state : A=20, B=10, temp=10)

B=A;            (This state : A=20, B=20, temp=10)

A=temp      (This state : A=10, B=20, temp=10)

By applying above logic you can swap values of two variables. In below Java example I will implement same logic two swap numbers.

Swap Numbers without Temporary Variable

There are two ways two swap two numbers without using any temporary variable.

Addition and Subtraction

Here you will see how to swap numbers A=20 and B=10 by using addition and subtraction operations.

A=A+B           (This state : A=30, B=10)

B=A-B           (This state : A=30, B=20)

A=A-B           (This state : A=10, B=20)

By applying above addition and subtraction logic you can swap values of two variables. In below Java example I will implement same logic two swap numbers.

Multiplication and Division

Here you will see how to swap numbers A=20 and B=10 by using multiplication and division operations.

A=A*B           (This state : A=200, B=10)

B=A/B           (This state : A=200, B=20)

A=A/B           (This state : A=10, B=20)

By applying above multiplication and division logic you can swap values of two variables. In below Java example I will implement same logic two swap numbers.

Swap Numbers Java Program

package test;

import java.util.Scanner;

public class SwapNumbers {

	public static void main(String[] args) {
		Scanner scan=new Scanner(System.in);
		System.out.println(&quot;Please Enter First Number&quot;);
		int A=scan.nextInt();

		System.out.println(&quot;Please Enter Second Number&quot;);
		int B=scan.nextInt();

		//swap Numbers with temporary variable
		swapNumbersWithTemp(A,B);
		//swap Numbers without temporary variable : Add and Sub
		swapNumbersWithoutTempAddSub(A,B);
		//swap Numbers without temporary variable : Mul and Div
		swapNumbersWithoutTempMulDiv(A,B);
	}

	private static void swapNumbersWithTemp(int A, int B)
	{
		int temp=B;
		B=A;
		A=temp;

		System.out.println(&quot;Numbers after swap with temporary variables&quot;);
		System.out.println(&quot;A=&quot;+A+&quot;and B=&quot;+B);
	}

	private static void swapNumbersWithoutTempAddSub(int A, int B)
	{
		A=A+B;
		B=A-B;
		A=A-B;

		System.out.println(&quot;Numbers after swap without temporary variables: Add and Sub operation&quot;);
		System.out.println(&quot;A=&quot;+A+&quot;and B=&quot;+B);
	}

	private static void swapNumbersWithoutTempMulDiv(int A, int B)
	{
		A=A*B;
		B=A/B;
		A=A/B;

		System.out.println(&quot;Numbers after swap without temporary variables: MUl and Div operation&quot;);
		System.out.println(&quot;A=&quot;+A+&quot;and B=&quot;+B);
	}

}

Output

Please Enter First Number
20
Please Enter Second Number
10
Numbers after swap with temporary variables
A=10and B=20
Numbers after swap without temporary variables: Add and Sub operation
A=10and B=20
Numbers after swap without temporary variables: MUl and Div operation
A=10and B=20
&lt;span 				data-mce-type=&quot;bookmark&quot; 				id=&quot;mce_SELREST_start&quot; 				data-mce-style=&quot;overflow:hidden;line-height:0&quot; 				style=&quot;overflow:hidden;line-height:0&quot; 			&gt;&lt;/span&gt;&lt;span 			

 

 

More Info

For more Algorithms and Java Programing Test questions and sample code follow below links

 

How to exclude fields from JSON while parsing by GSON/GsonBuilder?

In below previous exaxmples. We discussed about to convert JAVA object to/ from to JSON and pretty formatting and null serailization of fields for JSON conversion. Now here we discussed about how to exclude fields/object while converting to JSON.

How to convert Java object to / from JSON by (GSON)

How to do JSON pretty formatting and Null Serialization (GSON/GsonBuilder)

GSON provide two ways to exclude fields from JSON by GsonBuilder:

  • @Expose Annotation
  • Custom Annotation

@Expose Annotation

By using the @Expose annotations and then using the excludeFieldsWithoutExposeAnnotation() method on the GsonBuilder will ignore all fields except the ones that have been exposed using the @Expose annotation.

Custom Annotation

By defining a custom annotation and ignoring fields that are annotated with exclusion class by extending ExclusionStrategy interface implementing that by using below GsonBuilder methods can ingnore/exclude fields from JSON.

Boolean shouldSkipField(FieldAttributes f);

public boolean shouldSkipClass(Class clazz);

Pre-Requisite:

  • JAVA 8
  • Maven 3
  • GSON Jar as below.

GSON Dependency:

 &lt;dependency&gt;
    &lt;groupId&gt;com.google.code.gson&lt;/groupId&gt;
    &lt;artifactId&gt;gson&lt;/artifactId&gt;
    &lt;version&gt;2.8.2&lt;/version&gt;
 &lt;/dependency&gt;

In below example fields middleName,educationDetail and experienceDetail will not serialize because not having @Expose annotation on it and field country will also not serialize because of having @Country annotation. Here you will see how to unsearilize all these

package gsonexamples;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import model.AlbumImages;
import model.Albums;
import model.Country;
import model.Dataset;
import model.Employee;
import util.CustomExclusionStrategy;

class GsonConvertJavaObjectToJSONExclusion {

	public static void main(String[] args) {
		Employee employee= getJavaObject();
		//CustomExclusionStrategy that will exclude the Country field.
// We also allow only those fields that have been exposed using the @Expose
//annotation

				Gson gson = new GsonBuilder()
				.setPrettyPrinting()
				.serializeNulls()
				.setExclusionStrategies(new CustomExclusionStrategy(Country.class))
				.excludeFieldsWithoutExposeAnnotation()
				.create();

		System.out.println(gson.toJson(employee));

	}

	public static  Employee getJavaObject()
	{
		Employee employee=new Employee(&quot;C123&quot;,&quot;Saurabh&quot; ,&quot;Kumar&quot;,&quot;Gupta&quot;,&quot;Tech Lead&quot;,50000,&quot;Alpharetta,GA&quot;,&quot;Dallas, TX&quot;,&quot;1231231230&quot;,null,null);
		return employee;
	}

}

package util;

import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;

import model.Country;
import model.Dataset;

/**
 * This class use custom exclusion policy. We want to ignore all fields that
 * have been annotated with the Country annotation. Note that we can also ignore
 * fields based on name or type. This same type policy can be applied to any *  class.
 *
 */
public class CustomExclusionStrategy implements ExclusionStrategy {

	private Class classToExclude;

	public CustomExclusionStrategy(Class classToExclude) {
		this.classToExclude = classToExclude;
	}

	// This method is called for all fields. if the method returns false the
	// field is excluded from serialization
	//@Override
	public boolean shouldSkipField(FieldAttributes f) {
		if (f.getAnnotation(Country.class) == null)
			return false;

		return true;
	}

	// This method is called for all classes. If the method returns false the class is excluded.
	//@Override
	public boolean shouldSkipClass(Class&lt;?&gt; clazz) {
		if (clazz.equals(classToExclude))
			return true;
		return false;
	}

}
package model;

import java.util.List;
import java.util.Set;

import com.google.gson.annotations.Expose;

public class Employee {
	@Expose
	private String employeeId;
	@Expose
	private String firstName;
	private String middleName;
	@Expose
	private String lastName;
	@Expose
	private String designation;
	private int salary;
	@Expose
	private String permanentAddress;
	private String mailingAddress;
	@Country
	private String country;
	@Expose
	private String mobile;
	private Set&lt;Education&gt; educationDetail;
	private List&lt;Experience&gt; expericeDetail;

	@Override
	public String toString() {
		return &quot;Employee [employeeId=&quot; + employeeId + &quot;, firstName=&quot; + firstName + &quot;, middleName=&quot; + middleName
				+ &quot;, lastName=&quot; + lastName + &quot;, designation=&quot; + designation + &quot;, salary=&quot; + salary
				+ &quot;, permanentAddress=&quot; + permanentAddress + &quot;, mailingAddress=&quot; + mailingAddress + &quot;, mobile=&quot; + mobile
				+ &quot;, educationDetail=&quot; + educationDetail + &quot;, expericeDetail=&quot; + expericeDetail + &quot;]&quot;;
	}

	public Employee(String employeeId, String firstName, String middleName, String lastName, String designation,
			int salary, String permanentAddress, String mailingAddress, String mobile, Set&lt;Education&gt; educationDetail,
			List&lt;Experience&gt; expericeDetail) {
		super();
		this.employeeId = employeeId;
		this.firstName = firstName;
		this.middleName = middleName;
		this.lastName = lastName;
		this.designation = designation;
		this.salary = salary;
		this.permanentAddress = permanentAddress;
		this.mailingAddress = mailingAddress;
		this.mobile = mobile;
		this.educationDetail = educationDetail;
		this.expericeDetail = expericeDetail;
	}
//Getter and setter of fields
	}

package model;

public class Education {
private String schoolOrCollegeName;
private String standard;
private String stream;
private double percentage;

@Override
public String toString() {
	return &quot;Education [schoolOrCollegeName=&quot; + schoolOrCollegeName + &quot;, standard=&quot; + standard + &quot;, stream=&quot; + stream
			+ &quot;, percentage=&quot; + percentage + &quot;]&quot;;
}
public Education(String schoolOrCollegeName, String standard, String stream, double percentage) {
	super();
	this.schoolOrCollegeName = schoolOrCollegeName;
	this.standard = standard;
	this.stream = stream;
	this.percentage = percentage;
}
}
package model;

import java.util.Date;

public class Experience {
private String companyName;
private String designation;
private Date startDate;
private Date endDate;
private double salary;
public Experience(String companyName, String designation, Date startDate, Date endDate, double salary) {
	super();
	this.companyName = companyName;
	this.designation = designation;
	this.startDate = startDate;
	this.endDate = endDate;
	this.salary = salary;
}
@Override
public String toString() {
	return &quot;Experience [companyName=&quot; + companyName + &quot;, designation=&quot; + designation + &quot;, startDate=&quot; + startDate
			+ &quot;, endDate=&quot; + endDate + &quot;, salary=&quot; + salary + &quot;]&quot;;
}
//getter and setter
}

Output

{
  &quot;employeeId&quot;: &quot;C123&quot;,
  &quot;firstName&quot;: &quot;Saurabh&quot;,
  &quot;lastName&quot;: &quot;Gupta&quot;,
  &quot;designation&quot;: &quot;Tech Lead&quot;,
  &quot;permanentAddress&quot;: &quot;Alpharetta,GA&quot;,
  &quot;mobile&quot;: &quot;1231231230&quot;
}

Here in above JSON output for Employee class fields middleName, educationDetail and experienceDetail not printed because @Expose annotation was not given on that and by using CustomExlusionStartegy skiping serialization for fields country because it’s having @Country annotation as we remove in class for serialization CustomExclusionStrategy for @Country annotation.

Now in next example will discuss about.

How to parse JSON data token by token by using GSON/JsonToken/JsonReader?

How to do JSON pretty formatting and Null Serialization (GSON/GsonBuilder)

In previous example use GSON comes with simple JAVA API’s to convert JAVA object to/from JSON and here I will use GsonBuilder to print format JSON and serialize null object values also.

How to convert Java object to / from JSON by (GSON)

Pre-Requisite:

  • JAVA 8
  • Maven 3
  • GSON Jar as below.

GSON Dependency:

 &lt;dependency&gt;
    &lt;groupId&gt;com.google.code.gson&lt;/groupId&gt;
    &lt;artifactId&gt;gson&lt;/artifactId&gt;
    &lt;version&gt;2.8.2&lt;/version&gt;
 &lt;/dependency&gt;

Convert JAVA object to/from JSON

package gsonexamples;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import model.Employee;

public class GsonConvertJavaToJSON {

	public static void main(String[] args) {
		//Create GSON Object
		//Gson gson = new Gson();
Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls().create();
		Employee employee=getJavaObject();
		String json=gson.toJson(employee);

        System.out.println(&quot;Convert Java Object To JSON&quot;);
		System.out.println(json);

		System.out.println(&quot;Convert JSON To Java Object&quot;);
		employee=gson.fromJson(json,Employee.class);
		System.out.println(employee);

	}
	public static  Employee getJavaObject()
	{
		Employee employee=new Employee(&quot;C123&quot;,&quot;Saurabh&quot; ,&quot;Kumar&quot;,&quot;Gupta&quot;,&quot;Tech Lead&quot;,50000,&quot;Alpharetta,GA&quot;,&quot;Dallas, TX&quot;,&quot;1231231230&quot;,null,null);
		return employee;
	}

}

  • GsonBuilder().setPrettyPrinting() :  This api is to generate pretty formatted JSON string.
  • GsonBuilder().searializeNulls() :  This api is to serialize null values in object.
  • GsonBuilder().create(): This api is to create GSON object to Java object to/from JSON.
package model;

import java.util.List;
import java.util.Set;

public class Employee {
private String employeeId;
private String firstName;
private String middleName;
private String lastName;
private String designation;
private int salary;
private String permanentAddress;
private String mailingAddress;
private String mobile;
private Set&lt;Education&gt; educationDetail;
private List&lt;Experience&gt; expericeDetail;

@Override
public String toString() {
	return &quot;Employee [employeeId=&quot; + employeeId + &quot;, firstName=&quot; + firstName + &quot;, middleName=&quot; + middleName
			+ &quot;, lastName=&quot; + lastName + &quot;, designation=&quot; + designation + &quot;, salary=&quot; + salary + &quot;, permanentAddress=&quot;
			+ permanentAddress + &quot;, mailingAddress=&quot; + mailingAddress + &quot;, mobile=&quot; + mobile + &quot;, educationDetail=&quot;
			+ educationDetail + &quot;, expericeDetail=&quot; + expericeDetail + &quot;]&quot;;
}
public Employee(String employeeId, String firstName, String middleName, String lastName, String designation, int salary,
		String permanentAddress, String mailingAddress, String mobile, Set&lt;Education&gt; educationDetail,
		List&lt;Experience&gt; expericeDetail) {
	super();
	this.employeeId = employeeId;
	this.firstName = firstName;
	this.middleName = middleName;
	this.lastName = lastName;
	this.designation = designation;
	this.salary = salary;
	this.permanentAddress = permanentAddress;
	this.mailingAddress = mailingAddress;
	this.mobile = mobile;
	this.educationDetail = educationDetail;
	this.expericeDetail = expericeDetail;
}
//Getter and Setter
}

package model;

public class Education {
private String schoolOrCollegeName;
private String standard;
private String stream;
private double percentage;

@Override
public String toString() {
	return &quot;Education [schoolOrCollegeName=&quot; + schoolOrCollegeName + &quot;, standard=&quot; + standard + &quot;, stream=&quot; + stream
			+ &quot;, percentage=&quot; + percentage + &quot;]&quot;;
}
public Education(String schoolOrCollegeName, String standard, String stream, double percentage) {
	super();
	this.schoolOrCollegeName = schoolOrCollegeName;
	this.standard = standard;
	this.stream = stream;
	this.percentage = percentage;
}
//getter and setter
}
package model;

import java.util.Date;

public class Experience {
private String companyName;
private String designation;
private Date startDate;
private Date endDate;
private double salary;
public Experience(String companyName, String designation, Date startDate, Date endDate, double salary) {
	super();
	this.companyName = companyName;
	this.designation = designation;
	this.startDate = startDate;
	this.endDate = endDate;
	this.salary = salary;
}
@Override
public String toString() {
	return &quot;Experience [companyName=&quot; + companyName + &quot;, designation=&quot; + designation + &quot;, startDate=&quot; + startDate
			+ &quot;, endDate=&quot; + endDate + &quot;, salary=&quot; + salary + &quot;]&quot;;
}
//getter and setter
}

Output:

Convert Java Object To JSON
{
  &quot;employeeId&quot;: &quot;C123&quot;,
  &quot;firstName&quot;: &quot;Saurabh&quot;,
  &quot;middleName&quot;: &quot;Kumar&quot;,
  &quot;lastName&quot;: &quot;Gupta&quot;,
  &quot;designation&quot;: &quot;Tech Lead&quot;,
  &quot;salary&quot;: 50000,
  &quot;permanentAddress&quot;: &quot;Alpharetta,GA&quot;,
  &quot;mailingAddress&quot;: &quot;Dallas, TX&quot;,
  &quot;mobile&quot;: &quot;1231231230&quot;,
  &quot;educationDetail&quot;: null,
  &quot;expericeDetail&quot;: null
}
&lt;span 				data-mce-type=&quot;bookmark&quot; 				id=&quot;mce_SELREST_start&quot; 				data-mce-style=&quot;overflow:hidden;line-height:0&quot; 				style=&quot;overflow:hidden;line-height:0&quot; 			&gt;&lt;/span&gt;
Convert JSON To Java Object
Employee [employeeId=C123, firstName=Saurabh, middleName=Kumar, lastName=Gupta, designation=Tech Lead, salary=50000, permanentAddress=Alpharetta,GA, mailingAddress=Dallas, TX, mobile=1231231230, educationDetail=null, expericeDetail=null]

In above JSON output is pretty formatted properly and  serialize null objects for education and experience. In next blog will explain about how to exclude fields while serializing/deserializing to/from JSON by GsonBuilder.

How to exclude fields from JSON while parsing by GSON/GsonBuilder?

GSON Introduction

Gson is an open source Java library to serialize and de-serialize Java objects to/from JSON. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source code.

Initial Release : May 22,2008
Written in: Java
Developed By: Google
Stable Release : 2.8.2 in 19 Sep, 2017
License: Apache License 2.0

Why GSON is Popular?

  • provide simple methods toJson() and fromJson() to convert Java objects to JSON and vice-versa.
  • Extensive support of Java Generics.
  • allow custom representaion of objects.
  • allow pre-existing unmodifiable objects to be converted to and from JSON.
  • support for complex objects with generic types and having deep inheritance.

Configuration/Dependency

Below dependency required to configure GSON in your application

&lt;dependency&gt;
&lt;groupId&gt;com.google.code.gson&lt;/groupId&gt;
&lt;artifactId&gt;gson&lt;/artifactId&gt;
&lt;version&gt;2.8.2&lt;/version&gt;
&lt;/dependency&gt;

How to Convert JSON data from file to ArrayList?

Jackson provide api’s  to convert JSON data to Collections Objects like Map, ArrayList etc.

In below example file student_data.txt having collections of students data in JSON form and through these Jacson API’s will convert JSON data to ArrayList java object.

Pre-Requisite 

Add below jackson-databind-2.8.5.jar in your classpath or make dependency entry in pom.xml file.

  &lt;dependency&gt;
	&lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt;
	&lt;artifactId&gt;jackson-databind&lt;/artifactId&gt;
	&lt;version&gt;2.8.5&lt;/version&gt;
  &lt;/dependency&gt;
 

Sample Data

 Add below content in  student_data.txt

[
{
  &quot;rollNumber&quot; : 11,
  &quot;firstName&quot; : &quot;Saurabh&quot;,
  &quot;lastName&quot; : &quot;Gupta&quot;,
  &quot;permanent&quot; : false,
  &quot;address&quot; : {
    &quot;addressLine&quot; : &quot;Lake Union Hill Way&quot;,
    &quot;city&quot; : &quot;Atlanta&quot;,
    &quot;zipCode&quot; : 50005
  },
  &quot;phoneNumbers&quot; : [ 2233445566, 3344556677 ],
  &quot;cities&quot; : [ &quot;Dallas&quot;, &quot;San Antonio&quot;, &quot;Irving&quot; ],
  &quot;properties&quot; : {
    &quot;play&quot; : &quot;Badminton&quot;,
    &quot;interst&quot; : &quot;Math&quot;,
    &quot;age&quot; : &quot;34 years&quot;
  }
},
{
  &quot;rollNumber&quot; : 11,
  &quot;firstName&quot; : &quot;Gaurav&quot;,
  &quot;lastName&quot; : &quot;Khaira&quot;,
  &quot;permanent&quot; : true,
  &quot;address&quot; : {
    &quot;addressLine&quot; : &quot; 5770 Shiloh woods dr&quot;,
    &quot;city&quot; : &quot;Cumming&quot;,
    &quot;zipCode&quot; : 50007
  },
  &quot;phoneNumbers&quot; : [ 2233445567, 3344556678 ],
  &quot;cities&quot; : [ &quot;New York&quot;, &quot;Austin&quot;, &quot;Plano&quot; ],
  &quot;properties&quot; : {
    &quot;play&quot; : &quot;Baseball&quot;,
    &quot;interst&quot; : &quot;Science&quot;,
    &quot;age&quot; : &quot;36 years&quot;
  }
}
]

 

Example 

package test.facingissesonit.json.jacson;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;

import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class ConvertJsonToArrayList {

	public static void main(String[] args) {
		try
		{
		byte[] mapData = Files.readAllBytes(Paths.get(&quot;student_data.txt&quot;));
		Student[] studentArr = null;

		ObjectMapper objectMapper = new ObjectMapper();
		studentArr = objectMapper.readValue(mapData, Student[].class);
		List&lt;Student&gt; studentList=Arrays.asList(studentArr);
		System.out.println(&quot;Student 1 \n&quot;+studentList.get(0));
		System.out.println(&quot;Student 2 \n&quot;+studentList.get(1));

		}
		catch(JsonMappingException ex)
		{
			ex.printStackTrace();
		}
		catch(IOException ex)
		{
			ex.printStackTrace();
		}
	}
}

 

Model Classes

Below Student and Address are required classes for execute this code.

package test.facingissesonit.json.jacson;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class Student {
	private int rollNumber;
	private String firstName;
	private String lastName;
	private boolean permanent;
	private Address address;
	private long[] phoneNumbers;
	private List&lt;String&gt; cities;
	private Map&lt;String, String&gt; properties;
	@Override
	public String toString()
	{
		StringBuffer sb=new StringBuffer();
		sb.append(&quot;==============Student Information================\n&quot;);
		sb.append(&quot;rollNumber=&quot;).append(rollNumber).append(&quot;\n&quot;);
		sb.append(&quot;firstName=&quot;).append(firstName).append(&quot;\n&quot;);
		sb.append(&quot;lastName=&quot;).append(lastName).append(&quot;\n&quot;);
		sb.append(&quot;permanent=&quot;).append(permanent).append(&quot;\n&quot;);
		sb.append(&quot;adress=&quot;).append(address).append(&quot;\n&quot;);
		sb.append(&quot;phoneNumbers=&quot;).append(Arrays.toString(phoneNumbers)).append(&quot;\n&quot;);
		sb.append(&quot;cities=&quot;).append(Arrays.toString(cities.toArray(new String[cities.size()]))).append(&quot;\n&quot;);
		sb.append(&quot;properties=&quot;).append(properties).append(&quot;\n&quot;);
		return sb.toString();
	}
	public int getRollNumber() {
		return rollNumber;
	}
	public void setRollNumber(int rollNumber) {
		this.rollNumber = rollNumber;
	}
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public boolean isPermanent() {
		return permanent;
	}
	public void setPermanent(boolean permanent) {
		this.permanent = permanent;
	}
	public Address getAddress() {
		return address;
	}
	public void setAddress(Address address) {
		this.address = address;
	}
	public long[] getPhoneNumbers() {
		return phoneNumbers;
	}
	public void setPhoneNumbers(long[] phoneNumbers) {
		this.phoneNumbers = phoneNumbers;
	}
	public List&lt;String&gt; getCities() {
		return cities;
	}
	public void setCities(List&lt;String&gt; cities) {
		this.cities = cities;
	}
	public Map&lt;String, String&gt; getProperties() {
		return properties;
	}
	public void setProperties(Map&lt;String, String&gt; properties) {
		this.properties = properties;
	}

}

package test.facingissesonit.json.jacson;

public class Address {
private String addressLine;
private String city;
private String state;
private int zipCode;
@Override
public String toString()
{
	StringBuffer sb=new StringBuffer();
	sb.append(&quot;AddressLine=&quot;).append(addressLine).append(&quot;\n&quot;);
	sb.append(&quot;city=&quot;).append(city).append(&quot;\n&quot;);
	sb.append(&quot;state=&quot;).append(state).append(&quot;\n&quot;);
	sb.append(&quot;zipCode=&quot;).append(zipCode).append(&quot;\n&quot;);
	return sb.toString();
}
public String getAddressLine() {
	return addressLine;
}
public void setAddressLine(String addressLine) {
	this.addressLine = addressLine;
}
public String getCity() {
	return city;
}
public void setCity(String city) {
	this.city = city;
}
public String getState() {
	return state;
}
public void setState(String state) {
	this.state = state;
}
public int getZipCode() {
	return zipCode;
}
public void setZipCode(int zipCode) {
	this.zipCode = zipCode;
}
}

Output

Below is console output generated by program which is from Java Object.

Student 1
==============Student Information================
rollNumber=11
firstName=Saurabh
lastName=Gupta
permanent=false
adress=AddressLine=Lake Union Hill Way
city=Atlanta
state=null
zipCode=50005

phoneNumbers=[2233445566, 3344556677]
cities=[Dallas, San Antonio, Irving]
properties={play=Badminton, interst=Math, age=34 years}

Student 2
==============Student Information================
rollNumber=11
firstName=Gaurav
lastName=Khaira
permanent=true
adress=AddressLine= 5770 Shiloh woods dr
city=Cumming
state=null
zipCode=50007

phoneNumbers=[2233445567, 3344556678]
cities=[New York, Austin, Plano]
properties={play=Baseball, interst=Science, age=36 years}

More Sample Code

For more java and JDBC codes follow below links

How to Convert JSON to Java Object and Java Object to JSON?

In below java codes consider both the cases from JSON to Java Object and Java Object to JSON by ObjectMapper by Jacson API’s

I have given generic method for both the cases as convertJavaObjectToJSON and convertJSONToJavaObject.

Pre-Requisite : Add below jackson-databind-2.8.5.jar in your classpath or make dependency entry in pom.xml file.

  &lt;dependency&gt;
	&lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt;
	&lt;artifactId&gt;jackson-databind&lt;/artifactId&gt;
	&lt;version&gt;2.8.5&lt;/version&gt;
  &lt;/dependency&gt;
 

JAVA and JSON Conversion Example:

Below is complete example for conversion of both the cases.

ObjectMapper.readValue() :Convert JSON String to Java Object

ObjectMapper.writeValue() : Convert JAVA Object to JSON

package test.facingissesonit.json.jacson;

import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class JsonAndJavaObjectConversion {

	public static void main(String[] args) {
		System.out.println(&quot;=================Convert Student Java Object to JSON==============&quot;);
		// convert Object to json string
		Student student = sampleStudentObject();

		String studentStr = convertJavaObjectToJSON(student);
		System.out.println(&quot;Student JSON Data \n&quot; + studentStr);
		System.out.println(&quot;=================Convert JSON DATA  to Student JAVA Object==============&quot;);
		Object object = convertJSONToJavaObject(studentStr, Student.class);
		if (object != null &amp;&amp; object instanceof Student) {
			System.out.println(&quot;Student Object\n&quot; + (Student) object);
		}

	}
	//Generic Method to convert JSON object to Java Object
	public static Object convertJSONToJavaObject(String strJsonData, Class className) {
		try {
			// ObjectMapper new instance
			ObjectMapper objectMapper = new ObjectMapper();
			// //convert json data from file text to object
			return objectMapper.readValue(strJsonData, className);
		} catch (JsonMappingException ex) {
			ex.printStackTrace();
		} catch (JsonGenerationException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return null;
	}
    //Generic Method to convert Java object to JSON
	public static String convertJavaObjectToJSON(Object javaObject) {
		StringWriter jsonStr = null;
		try {

			// ObjectMapper new instance
			ObjectMapper objectMapper = new ObjectMapper();
			// configure Object mapper for pretty print
			objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);

			// writing to console, can write to any output stream such as file
			jsonStr = new StringWriter();
			objectMapper.writeValue(jsonStr, javaObject);

		} catch (JsonMappingException ex) {
			ex.printStackTrace();
		} catch (JsonGenerationException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return jsonStr.toString();
	}

	public static Student sampleStudentObject() {

		Student student = new Student();
		student.setRollNumber(11);
		student.setFirstName(&quot;Saurabh&quot;);
		student.setLastName(&quot;Gupta&quot;);
		student.setPhoneNumbers(new long[] { 2233445566L, 3344556677L });

		Address add = new Address();
		add.setAddressLine(&quot;Lake Union Hill Way&quot;);
		add.setCity(&quot;Atlanta&quot;);
		add.setState(&quot;GA&quot;);
		add.setZipCode(50005);
		student.setAddress(add);

		List&lt;String&gt; cities = new ArrayList&lt;String&gt;();
		cities.add(&quot;Dallas&quot;);
		cities.add(&quot;San Antonio&quot;);
		cities.add(&quot;Irving&quot;);
		student.setCities(cities);

		Map&lt;String, String&gt; props = new HashMap&lt;String, String&gt;();
		props.put(&quot;age&quot;, &quot;34 years&quot;);
		props.put(&quot;interst&quot;, &quot;Math&quot;);
		props.put(&quot;play&quot;, &quot;Badminton&quot;);

		student.setProperties(props);

		return student;
	}

}

Model Classes :

package test.facingissesonit.json.jacson;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class Student {
	private int rollNumber;
	private String firstName;
	private String lastName;
	private boolean permanent;
	private Address address;
	private long[] phoneNumbers;
	private List&lt;String&gt; cities;
	private Map&lt;String, String&gt; properties;
	@Override
	public String toString()
	{
		StringBuffer sb=new StringBuffer();
		sb.append(&quot;==============Student Information================\n&quot;);
		sb.append(&quot;rollNumber=&quot;).append(rollNumber).append(&quot;\n&quot;);
		sb.append(&quot;firstName=&quot;).append(firstName).append(&quot;\n&quot;);
		sb.append(&quot;lastName=&quot;).append(lastName).append(&quot;\n&quot;);
		sb.append(&quot;permanent=&quot;).append(permanent).append(&quot;\n&quot;);
		sb.append(&quot;adress=&quot;).append(address).append(&quot;\n&quot;);
		sb.append(&quot;phoneNumbers=&quot;).append(Arrays.toString(phoneNumbers)).append(&quot;\n&quot;);
		sb.append(&quot;cities=&quot;).append(Arrays.toString(cities.toArray(new String[cities.size()]))).append(&quot;\n&quot;);
		sb.append(&quot;properties=&quot;).append(properties).append(&quot;\n&quot;);
		return sb.toString();
	}
	public int getRollNumber() {
		return rollNumber;
	}
	public void setRollNumber(int rollNumber) {
		this.rollNumber = rollNumber;
	}
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public boolean isPermanent() {
		return permanent;
	}
	public void setPermanent(boolean permanent) {
		this.permanent = permanent;
	}
	public Address getAddress() {
		return address;
	}
	public void setAddress(Address address) {
		this.address = address;
	}
	public long[] getPhoneNumbers() {
		return phoneNumbers;
	}
	public void setPhoneNumbers(long[] phoneNumbers) {
		this.phoneNumbers = phoneNumbers;
	}
	public List&lt;String&gt; getCities() {
		return cities;
	}
	public void setCities(List&lt;String&gt; cities) {
		this.cities = cities;
	}
	public Map&lt;String, String&gt; getProperties() {
		return properties;
	}
	public void setProperties(Map&lt;String, String&gt; properties) {
		this.properties = properties;
	}

}

package test.facingissesonit.json.jacson;

public class Address {
private String addressLine;
private String city;
private String state;
private int zipCode;
@Override
public String toString()
{
	StringBuffer sb=new StringBuffer();
	sb.append(&quot;AddressLine=&quot;).append(addressLine).append(&quot;\n&quot;);
	sb.append(&quot;city=&quot;).append(city).append(&quot;\n&quot;);
	sb.append(&quot;state=&quot;).append(state).append(&quot;\n&quot;);
	sb.append(&quot;zipCode=&quot;).append(zipCode).append(&quot;\n&quot;);
	return sb.toString();
}
public String getAddressLine() {
	return addressLine;
}
public void setAddressLine(String addressLine) {
	this.addressLine = addressLine;
}
public String getCity() {
	return city;
}
public void setCity(String city) {
	this.city = city;
}
public String getState() {
	return state;
}
public void setState(String state) {
	this.state = state;
}
public int getZipCode() {
	return zipCode;
}
public void setZipCode(int zipCode) {
	this.zipCode = zipCode;
}
}

Output:

=================Convert Student Java Object to JSON==============
Student JSON Data
{
  &quot;rollNumber&quot; : 11,
  &quot;firstName&quot; : &quot;Saurabh&quot;,
  &quot;lastName&quot; : &quot;Gupta&quot;,
  &quot;permanent&quot; : false,
  &quot;address&quot; : {
    &quot;addressLine&quot; : &quot;Lake Union Hill Way&quot;,
    &quot;city&quot; : &quot;Atlanta&quot;,
    &quot;state&quot; : &quot;GA&quot;,
    &quot;zipCode&quot; : 50005
  },
  &quot;phoneNumbers&quot; : [ 2233445566, 3344556677 ],
  &quot;cities&quot; : [ &quot;Dallas&quot;, &quot;San Antonio&quot;, &quot;Irving&quot; ],
  &quot;properties&quot; : {
    &quot;play&quot; : &quot;Badminton&quot;,
    &quot;interst&quot; : &quot;Math&quot;,
    &quot;age&quot; : &quot;34 years&quot;
  }
}
=================Convert JSON DATA  to Student JAVA Object==============
Student Object
==============Student Information================
rollNumber=11
firstName=Saurabh
lastName=Gupta
permanent=false
adress=AddressLine=Lake Union Hill Way
city=Atlanta
state=GA
zipCode=50005

phoneNumbers=[2233445566, 3344556677]
cities=[Dallas, San Antonio, Irving]
properties={play=Badminton, interst=Math, age=34 years}

More Sample Code

For more java and JDBC codes follow below links

Java, How to convert List to Arrays and Array to ArrayList

In our day to day programming sometime use this conversion by using iteration but there is another way by using Java API’s as below.

ArrayList to Arrays

List provide toArray() method to convert list elements in Arrays.

List&lt;T&gt; list = new ArrayList&lt;T&gt;();
T[]arr=list.toArray(new T[list.size]);

Example :

import java.util.ArrayList;
import java.util.List;

public class ConvertArrayListToArray {

	public static void main(String[] args) {
		List&lt;String&gt; list = new ArrayList&lt;String&gt;();
		list.add(&quot;Georgia&quot;);
		list.add(&quot;Texas&quot;);
		list.add(&quot;Newyork&quot;);
		list.add(&quot;Okhlama&quot;);
		String [] states = list.toArray(new String[list.size()]);
	}

}

Arrays to ArrayList

Arrays class provide to asList() method to convert Array to immutable List So if you need to modify anything in List you will get java.lang.UnsupportedOperationException.

If you want to modification after convert to List then create with new ArrayList as below.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ConvertArrayToArrayList {

	public static void main(String[] args) {
		String [] states= {&quot;Georgia&quot;,&quot;Texas&quot;,&quot;New York&quot;, &quot;Okhlama&quot;};
		//Convert Array to immutable List
         List&lt;String&gt; stateList= Arrays.asList(states);
         try
         {
         stateList.add(&quot;North Carolina&quot;);
         }
         catch(UnsupportedOperationException ex)
         {
        	 ex.printStackTrace();
         }

         //Convert Array to mutable List
         stateList=new ArrayList&lt;String&gt;(Arrays.asList(states));
         stateList.add(&quot;North Carolina&quot;);
         System.out.println(stateList.get(4));
	}

}

In above example I have considered both cases for Immutable and Mutable.

More Sample Code

For more java and JDBC codes follow below links

[Solved] Elasticsearch “high disk watermark exceeded on one or more nodes”

This issue happen on Elasticsearch anytime   because your diskspace storage reached to more than 85% because in elasticsearch by default watermark is 85% of disk storage after reaching this limit elasticsearch stop working and print below warning in logs.

[2017-05-12T16:52:48,239][WARN ][o.e.c.r.a.DiskThresholdMonitor] [r78TO-I] high disk watermark [90%] exceeded on [r78TO-IgT9yPQQUgILl_5A][r78TO-I][C:\
Users\Facing Issues on IT\elasticsearch-5.4.0\data\nodes\0] free: 11.7gb[9.8%], shards will be relocat
ed away from this node
[2017-05-12T16:52:48,242][INFO ][o.e.c.r.a.DiskThresholdMonitor] [r78TO-I] rerouting shards: [high disk watermark exceeded on one or more nodes]
[2017-05-12T16:53:18,297][WARN ][o.e.c.r.a.DiskThresholdMonitor] [r78TO-I] high disk watermark [90%] exceeded on [r78TO-IgT9yPQQUgILl_5A][r78TO-I][C:\
Users\Facing Issues on IT\elasticsearch-5.4.0\data\nodes\0] free: 11.7gb[9.8%], shards will be relocat
ed away from this node
[2017-05-12T16:53:48,306][WARN ][o.e.c.r.a.DiskThresholdMonitor] [r78TO-I] high disk watermark [90%] exceeded on [r78TO-IgT9yPQQUgILl_5A][r78TO-I][C:\
Users\Facing Issues on IT\elasticsearch-5.4.0\data\nodes\0] free: 11.7gb[9.8%], shards will be relocat
ed away from this node

Solution :

We have to set below properties in config/elasticsearch.yml file for threshold value for disk storage , low and high watermark value.

cluster.routing.allocation.disk.threshold_enabled: true
cluster.routing.allocation.disk.watermark.low: 5gb
cluster.routing.allocation.disk.watermark.high: 2gb

Issues Solution

For more Elasticsearch issues solution follow link Common Elasticsearch Issues.