2

I have one problem.

let's say i have a model

public class Student{
     private int id;
     private String name;

   //getters and setters
}

Then i need to create 2 objects in different classes using Student model. In first class i need to create object with 2 fields, in second class with just one field.

public class ClassA{
     Student student = new Student();
     student.setId(id);
     student.setName(name);
}

and

public class ClassB{
     Student student = new Student();
     student.setId(id);
}

Then in second class even though i do not use second field, it is still being added as null.

How can I avoid this?

errordmas
  • 65
  • 1
  • 8

2 Answers2

1

You can use Jackson annotation to ignore null values in result JSON.

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

Read more here: https://www.baeldung.com/jackson-ignore-null-fields

Uladzislau Kaminski
  • 2,113
  • 2
  • 14
  • 33
1

If you are using the ObjectMapper to read the data you can ignore the unknown values as shown below.

ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);  
Rajesh
  • 4,273
  • 1
  • 32
  • 33