When to Use @JsonManagedReference and @JsonBackReference Annotations in Jackson

raja
Updated on 08-Jul-2020 11:36:22

5K+ Views

The @JsonManagedReference and @JsonBackReference annotations can be used to create a JSON structure in a bidirectional way. The @JsonManagedReference annotation is a forward reference that includes during the serialization process whereas @JsonBackReference annotation is a backreference that omits during the serialization process.In the below example, we can implement @JsonManagedReference and @JsonBackReference annotations.Exampleimport java.util.*; import com.fasterxml.jackson.annotation.JsonManagedReference; import com.fasterxml.jackson.annotation.JsonBackReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.core.JsonProcessingException; public class ManagedReferenceBackReferenceTest {    public static void main(String args[]) throws JsonProcessingException {       BackReferenceBeanTest testBean = new BackReferenceBeanTest(110, "Sai Chaitanya");       ManagedReferenceBeanTest bean = new ManagedReferenceBeanTest(135, "Adithya Ram", testBean);       testBean.addEmployees(bean);       ObjectMapper mapper = ... Read More

Check If Count of Divisors Is Even or Odd in Java

AmitDiwan
Updated on 08-Jul-2020 11:35:48

221 Views

To check if the count of divisors is even or odd, the Java code is as follows −Example Live Demoimport java.io.*; import java.math.*; public class Demo{    static void divisor_count(int n_val){       int root_val = (int)(Math.sqrt(n_val));       if (root_val * root_val == n_val){          System.out.println("The number of divisors is an odd number");       }else{          System.out.println("The number of divisors is an even number");       }    }    public static void main(String args[]) throws IOException{       divisor_count(25);    } }OutputThe number of divisors is an ... Read More

Convert JSON Object to Bean Using JSON-lib API in Java

raja
Updated on 08-Jul-2020 11:34:52

4K+ Views

The JSONObject class is a collection of name/value pairs (unordered) where the bean is a class with setter and getter methods for its member fields. We can convert a JSON object to a bean using the toBean() method of JSONObject class.Syntaxpublic static Object toBean(JSONObject jsonObject, Class beanClass)Exampleimport net.sf.json.JSONObject; public class ConvertJSONObjToBeanTest {    public static void main(String[] args) {       mployee emp = new Employee("Sai", "Ram", 30, "Bangalore");       JSONObject jsonObj = JSONObject.fromObject(emp);       System.out.println(jsonObj.toString(3)); // pretty print JSON       emp = (Employee)JSONObject.toBean(jsonObj, Employee.class);       System.out.println(emp.toString());    }    // Employee class    public static ... Read More

Smallest K-Digit Number Divisible by X in Java

AmitDiwan
Updated on 08-Jul-2020 11:23:11

219 Views

To find the smallest K digit number divisible by X, the Java code is as follows −Example Live Demoimport java.io.*; import java.lang.*; public class Demo{    public static double smallest_k(double x_val, double k_val){       double val = 10;       double MIN = Math.pow(val, k_val - 1);       if (MIN % x_val == 0)       return (MIN);       else       return ((MIN + x_val) - ((MIN + x_val) % x_val));    }    public static void main(String[] args){       double x_val = 76;       double k_val ... Read More

Convert Bean to XML Without Type Hints Using JSON-lib API in Java

raja
Updated on 08-Jul-2020 11:20:50

309 Views

The JSON-lib is a Java library for serializing and de-serializing java beans, maps, arrays, and collections in JSON format. We can convert a bean to XML without type hints using the setTypeHintsEnabled() method of XMLSerializer class, this method sets whether JSON types can be included as attributes. We can pass false as an argument to this method to disable the type hints in XML.Syntaxpublic void setTypeHintsEnabled(boolean typeHintsEnabled)Exampleimport net.sf.json.JSONObject; import net.sf.json.xml.XMLSerializer; public class ConvertBeanToXMLNoHintsTest {    public static void main(String[] args) {       Employee emp = new Employee("Krishna Vamsi", 115, 30, "Java");       JSONObject jsonObj = JSONObject.fromObject(emp);     ... Read More

Convert Bean to JSON Object Using Exclude Filter in Java

raja
Updated on 08-Jul-2020 11:20:06

494 Views

The JsonConfig class can be used to configure the serialization process. We can use the setJsonPropertyFilter() method of JsonConfig to set the property filter when serializing to JSON. We need to implement a custom PropertyFilter class by overriding the apply() method of the PropertyFilter interface. It returns true if the property will be filtered out or false otherwise.Syntaxpublic void setJsonPropertyFilter(PropertyFilter jsonPropertyFilter)Exampleimport net.sf.json.JSONObject; import net.sf.json.JsonConfig; import net.sf.json.util.PropertyFilter; public class ConvertBeanToJsonExcludeFilterTest {    public static void main(String[] args) {       Student student = new Student("Sai", "Chaitanya", 20, "Hyderabad");       JsonConfig jsonConfig = new JsonConfig();       jsonConfig.setJsonPropertyFilter(new CustomPropertyFilter());       ... Read More

Convert Bean to XML Using JSON-lib API in Java

raja
Updated on 08-Jul-2020 11:16:03

364 Views

The net.sf.json.xml.XMLSerializer class is a utility class for transforming JSON to XML. When transforming JSONObject instance to XML, this class can add hints for converting back to JSON. We can use the write() method of XMLSerializer class to write a JSON value into an XML string with UTF-8 encoding and it can return a string representation of a well-formed XML document.Syntaxpublic String write(JSON json)Exampleimport net.sf.json.JSONObject; import net.sf.json.xml.XMLSerializer; public class ConvertBeanToXMLTest {    public static void main(String[] args) {       Student student = new Student("Sai", "Adithya", 25, "Pune");       JSONObject jsonObj = JSONObject.fromObject(student);       System.out.println(jsonObj.toString(3)); //pretty print JSON ... Read More

Java Program for N-th Fibonacci Number

AmitDiwan
Updated on 08-Jul-2020 10:38:54

5K+ Views

There are multiple ways in which the ‘n’thFibonacci number can be found. Here, we will use dynamic programming technique as well as optimizing the space.Let us see an example −Example Live Demopublic class Demo{    static int fibo(int num){       int first = 0, second = 1, temp;       if (num == 0)       return first;       if (num == 1)       return second;       for (int i = 2; i

Replacing Public with Private in Main Method in Java

AmitDiwan
Updated on 08-Jul-2020 10:33:09

409 Views

When ‘public’ is used in ‘main’ −Example Live Demopublic class Demo{    public static void main(String args[]){       System.out.println("This is a sample only");    } }OutputThis is a sample onlyA class named Demo contains the main function that is public. It has a print function, which successfully compiles, executes and prints the message on the console.When ‘public’ is replaced with ‘private’Example Live Demopublic class Demo{    private static void main(String args[]){       System.out.println("This is a sample only");    } }OutputError: Main method not found in class Demo, please define the main method as: public static void main(String[] args) ... Read More

Replace Null Values with Default Value in Java Map

AmitDiwan
Updated on 08-Jul-2020 10:29:55

1K+ Views

To replace null values with default value in Java Map, the code is as follows −Example Live Demoimport java.util.*; import java.util.stream.*; public class Demo{    public static Map null_vals(Map my_map, T def_val){       my_map = my_map.entrySet().stream().map(entry -> {          if (entry.getValue() == null)          entry.setValue(def_val);          return entry;       })       .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));       return my_map;    }    public static void main(String[] args){       Map my_map = new HashMap();       my_map.put(1, null);       my_map.put(2, 56);   ... Read More

Advertisements