How to pass different constructors as response in java

java 8 constructor reference with arguments
java 8 pass method as parameter
java pass method as parameter
passing lambda as parameter java
java method reference with multiple parameters
java pass function as parameter
java supplier
java how to return supplier

Response.java

public class Response{

private String mobileNo;
private String contractId;
private String sim;
private String imei;

public Response(String mobileNo, String contractId){
    this.mobileNo = mobileNo;
    this.contractId = contractId;

}

public Response(String mobileNo, String contractId, String sim,
        String imei, String identificationType) {
    this.mobileNo = mobileNo;
    this.contractId = contractId;
    this.sim = sim;
    this.imei = imei;
    this.identificationType = identificationType;
}



//Getter and Setter

}

MainEx.java

public class MainEx{

   Response  response = null;  

   public Response response(){

     String mobileNo = null;
     String contractId = null;
     String sim = null;
     String imei = null;

     if(something){
        response= new IVRAccountDetailsRs("777","4545"); 
     }
     else{
        response= new IVRAccountDetailsRs("777","4545","sim","imei");
     }
    return response;
   }
}

When if statement call return response as

{ "mobileNo" = "777";
  "contractId" = "4545";
  "sim"= null;
  "imei" = null;
}

But I want to get the response as bellow,

When calling if statement

Need to remove other two values.

{ "mobileNo" = "777";
  "contractId" = "4545";
}

If contractId and mobileNo null then output should be

{ "mobileNo" = null;
  "contractId" = null;
}

When calling else statement

{ "mobileNo" = "777";
  "contractId" = "4545";
  "sim"= "sim";
  "imei" = "imei";
}

if all values null

 { "mobileNo" = null;
      "contractId" = null;
      "sim"= null;
      "imei" =null;
    }

Used Jackson version is 2.4.1

What can I do about this?

What you ask it's not possible to manage just with serialization.

I suggest to edit Response class, removing the field that don't want send when they are null.

Then create another class that extends Response, that have the other 2 fields.

At this point you can instantiate which one you want based on your condition and return anyway as a Response object.

public class SimpleResponse {
    String mobileNo;
    String contractId;

    .....getters setters
}



public class FullResponse extends SimpleResponse {
    String sim;
    String imei;

    ....getter and setters
}

Java 8 Supplier with arguments in the constructor, That's just a limitation of the method reference syntax -- that you can't pass in On the other hand Supplier<T> 's T get() is isomorphic to a zero arg constructor. When we do not pass arguments in the constructor, that constructor is known as a non- parameterized or no-argument constructor. When the programmer does not define any constructor in the Java program then the Java compiler itself adds a constructor in it, known as default constructor which provides default values to the object like 0, null, etc.

If the version of SpringBoot is less than 1.3, it can only be handled programmatically

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
public class Response {
    ///~
}

Spring boot can be configured directly from 1.3 in the application.properties file

spring.jackson.default-property-inclusion=non_null

Official documentation for the jacksong configuration

you can use @JsonInclude(JsonInclude.Include.NON_NULL) on sim and imei, Not on the whole class

public class Response{

private String mobileNo;
private String contractId;
@JsonInclude(JsonInclude.Include.NON_NULL)
private String sim;
@JsonInclude(JsonInclude.Include.NON_NULL)
private String imei;

public Response(String mobileNo, String contractId){
    this.mobileNo = mobileNo;
    this.contractId = contractId;

}

public Response(String mobileNo, String contractId, String sim,
        String imei, String identificationType) {
    this.mobileNo = mobileNo;
    this.contractId = contractId;
    this.sim = sim;
    this.imei = imei;
    this.identificationType = identificationType;
}

5.2. Writing Constructors, 5.13 Free Response Question (FRQ) for Classes · 5.14 Free Response Question - Time Here are two constructors that could be written for the Person class. written for a class, Java provides a no-argument default constructor where the (Advanced Topic Warning) When you pass object references as parameters to  Constructor(s) of a class must has same name as the class name in which it resides. A constructor in Java can not be abstract, final, static and Synchronized. Access modifiers can be used in constructor declaration to control its access i.e which other class can call the constructor.

If you use jackson then add this:

@JsonInclude(JsonInclude.Include.NON_NULL) before field.

public class Response{

private String mobileNo;
private String contractId;
@JsonInclude(JsonInclude.Include.NON_NULL)
private String sim;
@JsonInclude(JsonInclude.Include.NON_NULL)
private String imei;
}

Java Quiz 4: Passing a Parameter to a Constructor, This program writes "16" to the standard output. The correct answer and its explanation will be included in the next quiz in two weeks! For more  A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. The constructor is called when an object of a class is created.

For jackson serializers:

You can use annotation over your class, to skip serializing null values:

@JsonInclude(Include.NON_NULL)
public class Response{...}

Or add a parameter to your ObjectMapper configuration:

mapper.setSerializationInclusion(Include.NON_NULL);

This may be a duplicate.

UPDATE:

You can also annotate properties.

@JsonInclude(JsonInclude.Include.NON_NULL)
private String sim;
@JsonInclude(JsonInclude.Include.NON_NULL)
private String imei;

This way other properties will serialize null values, but those two will not be serialized with null value.

The Builder Design Pattern in Java, In the JavaBeans pattern, we call a no-arg constructor to create an object But, this solution has two big disadvantages: the first one is that the object the private constructor in the outer class, passing the Builder object itself  A constructor in Java is a block of code similar to a method that’s called when an instance of an object is created. Here are the key differences between a constructor and a method: A constructor doesn’t have a return type. The name of the constructor must be the same as the name of the class. Unlike methods,

Add this annotation just above the getter of sim and imei

 @JsonInclude(Include.NON_NULL)

With Jackson > 1.9.11 and < 2.x use

  @JsonSerialize 

annotation to do that:

   @JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)

For the version above 2:

 @JsonInclude(JsonInclude.Include.NON_NULL)

JAX-RS - Resource Constructors, getRequestUri(); return String.format(" response from: %s%n PathNum: %s%n q: Also it is not possible to pass request time parameters during the construction time in the Application subclass: If there are various constructors with the same number of parameters then the it's up to Core Java Tutorials. Constructor overloading is a concept of having more than one constructor with different parameters list, in such a way so that each constructor performs a different task. Refer constructor overloading with example for more details with example. Java Copy Constructor. A copy constructor is used for copying the values of one object to another object.

5 ways to Return multiple values from a method in Java, In this post, we will see how to return multiple values from a function in Java using variables and a public constructor to initiate its fields with required values or a but it doesn't offer any type safety or even pass field information to the caller. In Java, a constructor is said to be default constructor if it does not have any parameter. Default constructor can be either user defined or provided by JVM. If a class does not contain any constructor then during runtime JVM generates a default constructor which is known as system define default constructor.

Passing Information to a Method or a Constructor (The Java , or with yet a different number of arguments. Parameter Names. When you declare a parameter to a method or a constructor, you provide a name for that parameter. A constructor is a special method that is invoked when a new object is created. If we want to perform any one-time activities on an object at the time of its creation, then the constructor is the right place. Generally, the initialization of instance variables are done in the constructor. The purpose of a constructor

Java Fundamentals Tutorial: Object Oriented Programming in Java, Java variables do not contain the actual objects, they contain references to the objects. We'll discuss examples of overloading constructors and other methods later in this Parameters passed into methods are always copied (“pass-by-​value”). actions such as notifications in response to data access and modification. As with methods, the Java platform differentiates constructors on the basis of the number of arguments in the list and their types. You cannot write two constructors that have the same number and type of arguments for the same class, because the platform would not be able to tell them apart.

Comments
  • You are using gson?
  • which libary you used to serialization
  • "But I want to get the response as bellow when calling if statement." => The real question is: Why?
  • @Dev4World what r u using? Gson or Jackson
  • @Dev4World you can use @JsonInclude(JsonInclude.Include.NON_NULL) on sim and imei, Not on the whole class
  • When I use like this if some values null in the else statement those values remove from the response. But I need those null values with else statement response. Please check my updated question.
  • Check again my answer
  • Maybe you have newer version of Jackson, put annotation above getter of filed that want ignore when is null
  • Jackson version is 2.4.1
  • Check this added answer part
  • I tried with your updated answer. Butt issue is same. I also updated my question.