public boolean isValidDateFormat(String format, String value) {
Date date = null;
try {
SimpleDateFormat sdf = new SimpleDateFormat(format);
date = sdf.parse(value);
if (!value.equals(sdf.format(date))) {
date = null;
}
} catch (ParseException e) {
e.printStackTrace();
}
return date != null;
}
Tuesday, April 1, 2025
Check the date format of value
Monday, March 24, 2025
JSON Using Jackson API
Maven Dependency:
<!-- jackson-databind jar -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.18.3</version>
</dependency>
Class ObjectMapper:
// Create an object to ObjectMapper ObjectMapper objectMapper = new ObjectMapper();
Create a JSON Object or Object Node:
It is similar to map put method. put method is overloaded to accept different types of data
// Creating Node that maps to JSON Object structures in JSON content ObjectNode bookingDetails = objectMapper.createObjectNode();
// String as field value
bookingDetails.put("firstname", "Jim");
bookingDetails.put("lastname", "Brown");
// integer as field value
bookingDetails.put("totalprice", 111);
// boolean as field value
bookingDetails.put("depositpaid", true);
bookingDetails.put("additionalneeds", "Breakfast");Note: Duplicate field name. Will override the value.
bookingDetails.put("additionalneeds", "Lunch");// To print created json object
String createdPlainJsonObject = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(bookingDetails);
System.out.println("Created plain JSON Object is : \n"+ createdPlainJsonObject);Output :–
Created plain JSON Object is :
{
"firstname" : "Jim",
"lastname" : "Brown",
"totalprice" : 111,
"depositpaid" : true,
"additionalneeds" : "Lunch"
}Create a nested JSON Object or Object Node:
// Since requirement is to create a nested JSON Object
ObjectNode bookingDateDetails = objectMapper.createObjectNode();
bookingDateDetails.put("checkin", "2021-07-01");
bookingDateDetails.put("checkout", "2021-07-01");We use set(String fieldName, JsonNode fieldValue) or replace(String fieldName, JsonNode fieldValue)
bookingDetails.set("bookingdates", bookingDateDetails);// To get the created json object as string. Use writerWithDefaultPrettyPrinter() for proper formatting
String createdNestedJsonObject = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(bookingDetails);
System.out.println("Created nested JSON Object is : \n"+ createdNestedJsonObject); Output:
Created nested JSON Object is :
{
"firstname" : "Jim",
"lastname" : "Brown",
"totalprice" : 111,
"depositpaid" : true,
"additionalneeds" : "Lunch",
"bookingdates" : {
"checkin" : "2021-07-01",
"checkout" : "2021-07-01"
}
} Retrieve a field value from JSON Object or ObjectNode:
We can retrieve field value by passing field name. Since it is string, use asText().
String firstName = bookingDetails.get("firstname").asText();
System.out.println("First name is : "+firstName);
// We can use asText() as well but return type will be string
boolean depositpaid = bookingDetails.get("depositpaid").asBoolean();
System.out.println("deposit paid is : "+depositpaid);
// To retrieve value of nested ObjectNode
bookingDetails.get("bookingdates").get("checkin").asText();
System.out.println("Checkin date is : "+depositpaid);Output:
First name is : Jim deposit paid is : true Checkin date is : 2021-07-01
Retrieve all field names from JSON Object or Object Node:
To retrieve all field names from a ObjectNode, we need to use fieldNames() methods which returns an Iterator<String>.
// To get all field names
System.out.println("Count of fields in ObjectNode : "+ bookingDetails.size());
Iterator allFieldNames = bookingDetails.fieldNames();
System.out.println("Fields are : ");
while(allFieldNames.hasNext())
{
System.out.println(allFieldNames.next());
}Output:
Count of fields in ObjectNode : 6 Fields are : firstname lastname totalprice depositpaid additionalneeds bookingdates
Retrieve all field values from from JSON Object or ObjectNode:
To retrieve all field values from an ObjectNode, use elements() method which returns an Iterator of JsonNode.
// To get all field values
Iterator allFieldValues = bookingDetails.elements();
System.out.println("Fields values are : ");
while(allFieldValues.hasNext())
{
System.out.println(allFieldValues.next());
}Output:
Fields values are :
"Jim"
"Brown"
111
true
"Lunch"
{"checkin":"2021-07-01","checkout":"2021-07-01"}Retrieve all key-value pair from JSON Object or ObjectNod:
We can use fields() method to get all fields (with both names and values) of a JSON Object. It returns an Iterator<Entry<String,JsonNode>>.
// To get all key-value pair
Iterator> allFieldsAndValues = bookingDetails.fields();
System.out.println("All fields and their values are : ");
while(allFieldsAndValues.hasNext())
{
Entry node = allFieldsAndValues.next();
System.out.println("Key is : "+node.getKey()+" and its value is : "+node.getValue());
}Output:
All fields and their values are :
Key is : firstname and its value is : "Jim"
Key is : lastname and its value is : "Brown"
Key is : totalprice and its value is : 111
Key is : depositpaid and its value is : true
Key is : additionalneeds and its value is : "Lunch"
Key is : bookingdates and its value is : {"checkin":"2021-07-01","checkout":"2021-07-01"}Remove a field from JSON Object or ObjectNode:
Use remove(String fieldName) method to remove a field from ObjectNode. It will return value of the field, if such field existed; null if not.
// To remove a field
String removedFieldValue = bookingDetails.remove("firstname").asText();
System.out.println("Value of Removed field is " + removedFieldValue);
String removedJsonObject = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(bookingDetails);
System.out.println("After removing field , JSON Object is : \n"+ removedJsonObject);Output:
Value of Removed field is Jim
After removing field , JSON Object is :
{
"lastname" : "Brown",
"totalprice" : 111,
"depositpaid" : true,
"additionalneeds" : "Lunch",
"bookingdates" : {
"checkin" : "2021-07-01",
"checkout" : "2021-07-01"
}
}Update a field from JSON Object or ObjectNode:
We need to use put() method to update a field value if fieldValue is not another ObjectNode. If fieldValue is an ObjectNode use set() or replace() method.
// To replace a field value, use put() method for non ObjectNode type and replace() or set() for ObjectNode
bookingDetails.put("firstname", "Amod");
bookingDetails.put("firstname", "Aaditya");
String updatedJsonObject = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(bookingDetails);
System.out.println("After updating field , JSON Object is : \n"+ updatedJsonObject);Output:
After updating field , JSON Object is :
{
"lastname" : "Brown",
"totalprice" : 111,
"depositpaid" : true,
"additionalneeds" : "Lunch",
"bookingdates" : {
"checkin" : "2021-07-01",
"checkout" : "2021-07-01"
},
"firstname" : "Aaditya"
}JSON Array:
create JSON Array we use createArrayNode() method of ObjectMapper class. createArrayNode() will return reference of ArrayNode class.
- Create an empty JSON Array.
- Create first JSON Object
- Create second JSON Object
- Add created JSON Objects to JSON Array
// Create an array Node
ArrayNode arrayNode = objectMapper.createArrayNode();//add our elements directly to array
arrayNode.add("Apple").add("Banana").add("Cherry");// Update an array Node
ArrayNode arrayNode = (ArrayNode) objectMapper.readTree(arrayNode);
arrayNode.set(1, "Blueberry");This test demonstrates reading a JSON array into an ArrayNode and updating the value at index one from “Banana” to “Blueberry“.
Finally, we use the set() method to directly replace the value with a String, and Jackson automatically handles the conversion to a TextNode internally.
// Create an array ArrayNode parentArray = objectMapper.createArrayNode();
Add created JSON Objects to JSON Array:
Class ArrayNode provides a method add() which can add one JSON Object to array at a time.
parentArray.add(firstBookingDetails); parentArray.add(secondBookingDetails);
To add multiple Object Nodes to array at a time we can use addAll() method which accepts a Collection<? extends JsonNode> . We can create a List (because List extends Collection)of all JSON Objects and add.
parentArray.addAll(Arrays.asList(firstBookingDetails,secondBookingDetails));
String jsonArrayAsString = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(parentArray); System.out.println(jsonArrayAsString);
Note:- If you try to add duplicate Object Nodes, it will be added to array.
Retrieving JSON Object from JSON array using index:
// To get json array element using index JsonNode firstElement = parentArray.get(0); System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(firstElement));
Get size of JSON Array:
size() method can be used to get size of JSON Array.
int sizeOfArray = parentArray.size();
System.out.println("Size of array is "+sizeOfArray);Iterate JSON Array:
iterator() method can be used to iterate through a JSON Array.
// To iterate JSON Array
Iterator iteraor = parentArray.iterator();
System.out.println("Prining Json Node using iterator : ");
while(iteraor.hasNext())
{
JsonNode currentJsonNode = iteraor.next();
System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(currentJsonNode));
}
Remove a JSON Object from JSON Array:
We can remove a JSON object from JSON Array using its index.
// To remove an element from array
parentArray.remove(0);
System.out.println("After removing first element from array : "+ objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(parentArray));
Empty JSON Array:
// To empty JSON Array
parentArray.removeAll();
System.out.println("After removing all elements from array : "+ objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(parentArray));
Subscribe to:
Comments (Atom)