This is my JSON response which I need to store in realm.
{
"account": {
"_id": "xx123",
"user_id": "abc999",
"accounts": [
{
"email": "random12#gmail.com",
"email_platform": [
"email"
]
}
]
}
}
As we can not store List<String> I have created a custom class for string value using this example but it gives me following error
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 199 path $.data.account.accounts[0].email_platform[0]:
public class StringClassEmail extends RealmObject{
private String emailVal;
public StringClassEmail() {
}
public StringClassEmail(String emailVal) {
this.emailVal = emailVal;
}
}
here is also accounst class if required
public class UserAccountList extends RealmObject {
#SerializedName("email")
#Expose
private String email;
#SerializedName("email_platform")
#Expose
private RealmList<StringClassEmail> emailPlatform;
//getter and setter
}
First you should generate your DTOs with jsonschema2pojo
-----------------------------------com.example.Account.java-----------------------------------
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class AccountDTO {
#SerializedName("_id")
#Expose
private String id;
#SerializedName("user_id")
#Expose
private String userId;
#SerializedName("accounts")
#Expose
private List<EmailDTO> emails = null;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public List<EmailDTO> getEmails() {
return emails;
}
public void setAccounts(List<EmailDTO> emails) {
this.emails = emails;
}
}
-----------------------------------com.example.Account_.java-----------------------------------
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class EmailDTO {
#SerializedName("email")
#Expose
private String email;
#SerializedName("email_platform")
#Expose
private List<String> emailPlatform = null;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public List<String> getEmailPlatform() {
return emailPlatform;
}
public void setEmailPlatform(List<String> emailPlatform) {
this.emailPlatform = emailPlatform;
}
}
-----------------------------------com.example.Response.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Response {
#SerializedName("account")
#Expose
private AccountDTO account;
public AccountDTO getAccount() {
return account;
}
public void setAccount(AccountDTO account) {
this.account = account;
}
}
Then define RealmObject classes as well
public class Account extends RealmObject {
#PrimaryKey
private String id;
#Index
private String userId;
private User user;
private RealmList<Email> emails = null;
}
public class Email extends RealmObject {
#Index
private String email;
private RealmList<EmailPlatform> emailPlatform;
}
public class EmailPlatform extends RealmObject {
#Index
private String platform;
private Email email;
}
And then parse the JSON with GSON, then map it over to Realm's schema, then insert it to db.
Related
I'm trying to develop an API with an order model and one of the requirements in my model is "price" which takes a float instead of a string
this is the model
package com.api.order_control.models;
import jakarta.persistence.*;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.UUID;
#Entity
#Table(name = "TB_ORDER")
public class OrderModel implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private UUID id;
#Column(nullable = false, length = 11)
private String customerName;
#Column(nullable = false, length = 15)
private String phoneNumber;
#Column(nullable = false, length = 25)
private String address;
#Column(nullable = false, length = 10)
private String doorNumber;
#Column(nullable = true, length = 5)
private String block;
#Column(nullable = false, length = 30)
private String order;
#Column(nullable = false)
private Float price;
#Column(nullable = false)
private LocalDateTime registrationDate;
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDoorNumber() {
return doorNumber;
}
public void setDoorNumber(String doorNumber) {
this.doorNumber = doorNumber;
}
public String getBlock() {
return block;
}
public void setBlock(String block) {
this.block = block;
}
public String getOrder() {
return order;
}
public void setOrder(String order) {
this.order = order;
}
public Float getPrice() {
return price;
}
public void setPrice(Float price) {
this.price = price;
}
public LocalDateTime getRegistrationDate() {
return registrationDate;
}
public void setRegistrationDate(LocalDateTime registrationDate) {
this.registrationDate = registrationDate;
}
}
this is the dto package
package com.api.order_control.dtos;
import jakarta.validation.constraints.NotBlank;
public class OrderDto {
#NotBlank
private String customerName;
#NotBlank
private String phoneNumber;
#NotBlank
private String address;
#NotBlank
private String doorNumber;
#NotBlank
private String block;
#NotBlank
private String order;
#NotBlank
private Float price;
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String doorNumber() {
return doorNumber;
}
public void doorNumber(String doorName) {
this.doorNumber = doorName;
}
public String getBlock() {
return block;
}
public void setBlock(String block) {
this.block = block;
}
public String getOrder() {
return order;
}
public void setOrder(String order) {
this.order = order;
}
public Float getPrice() {
return price;
}
public void setPrice(Float price) {
this.price = price;
}
}
I created my post method in my controller, but when I test it in my postman I get this error in the terminal:
jakarta.validation.UnexpectedTypeException: HV000030: No validator could be found for constraint 'jakarta.validation.constraints.NotBlank' validating type 'java.lang.Float'. Check configuration for 'price'
I understand that the problem is in float, but I can't understand what's wrong with this code.
update: controller
package com.api.order_control.controllers;
import com.api.order_control.dtos.OrderDto;
import com.api.order_control.models.OrderModel;
import com.api.order_control.services.OrderService;
import jakarta.validation.Valid;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.time.ZoneId;
#RestController
#CrossOrigin(origins = "*", maxAge = 3600)
#RequestMapping("/order")
public class OrderController {
final OrderService orderService;
public OrderController(OrderService orderService) {
this.orderService = orderService;
}
#PostMapping
public ResponseEntity<Object> saveOrder(#RequestBody #Valid OrderDto orderDto) {
var orderModel = new OrderModel();
BeanUtils.copyProperties(orderDto, orderModel);
orderModel.setRegistrationDate(LocalDateTime.now(ZoneId.of("UTC")));
return ResponseEntity.status(HttpStatus.CREATED).body(orderService.save(orderModel));
}
}
You need to use #NotNull for Float. The documentation for #NotBlank states:
The annotated element must not be null and must contain at least one non-whitespace character. Accepts CharSequence.
So, as long as you don't use #NotBlank on a String or Char it won't work.
If you need additional validations on the value of the float, you can use #Min, #Max, #Positive and more.
I have a model class like the following:
package com.example.model;
import java.util.Map;
import javax.persistence.Column;
import javax.persistence.Convert;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import com.example.helpers.StringMapConverter;
#Entity
#Table(name = "buildingcompanies")
public class Buildcompanies {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#Column(name = "shortname")
private String shortname;
#Column(name = "fullname")
private String fullname;
#Column(name = "address")
private String address;
#Column(name = "telephone")
private String telephone;
#Column(name = "website")
private String website;
#Column(name = "sociallinks")
#Convert(converter = StringMapConverter.class)
private Map<String, String> sociallinks;
#Column(name = "foundationyear")
private String foundationyear;
public Buildcompanies() {
}
public Buildcompanies(String shortname, String fullname, String address, String telephone, String website,
Map<String, String> map, String foundationyear) {
this.shortname = shortname;
this.fullname = fullname;
this.address = address;
this.telephone = telephone;
this.website = website;
this.sociallinks = map;
this.foundationyear = foundationyear;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getShortname() {
return shortname;
}
public void setShortname(String shortname) {
this.shortname = shortname;
}
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public Map<String, String> getSociallinks() {
return sociallinks;
}
public void setSociallinks(Map<String, String> sociallinks) {
this.sociallinks = sociallinks;
}
public String getFoundationyear() {
return foundationyear;
}
public void setFoundationyear(String foundationyear) {
this.foundationyear = foundationyear;
}
}
And the method in a controller to show the output:
public ResponseEntity<List<Buildcompanies>> getAllCompanies(#RequestParam(required = false) String name) {
try {
List<Buildcompanies> companies = new ArrayList<Buildcompanies>();
int test=0;
if (name == null)
{
buildcompaniesRepository.findAll().forEach(companies::add);
}
else
buildcompaniesRepository.findByShortnameContaining(name).forEach(companies::add);
if (companies.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<>(companies, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
It does show an output everythin is just fine:
[
{
"id": 81,
"shortname": "testing",
"fullname": "test",
"address": "addrtest",
"telephone": "380979379992",
"website": "www.site.com",
"sociallinks": {
"facebook": "fb.com"
},
"foundationyear": "1991"
}
]
And I want to calculate each companies rating while showing data to the end user. So the output should be as follows:
[
{
"id": 81,
"shortname": "testing",
"fullname": "test",
"address": "addrtest",
"telephone": "380979379992",
"website": "www.site.com",
"sociallinks": {
"facebook": "fb.com"
},
"foundationyear": "1991",
"rating": "1.5"
}
]
Is it posible to add the rating column dynamicly to the company list or I should to create rating column in database, update method for it in the controller, iterate over the findAll() results and call it each time user tryes to acces /list endpoint?
You have two options:
You may introduce a new attribute in the Buildcompanies class for the purpose and annotate it with #Transient.
This will denote that the attribute need not be persisted in the DB and JPA won't attempt to create a column in the table.
The recommended approach is to not use the Entity class as a response object. You should ideally have a domain object and the database response should be mapped to this object. While mapping you can apply whatever custom details you want to add to it.
Just add #Transient annotation to your dynamic field. There is no corresponding column required in the database. The value of the transient column exists only in runtime.
In general, it is a bad idea to share the entity as a JSON with an external system for many reasons. Use intermediate DTO instead. There are a lot of libraries that allow configurable auto-mapping from entity to DTO (ModelMapper is pretty good for me).
I would like to get the value of my database with the getter getName().
First, I have created User.java:
package ch.concertopro.webshopanalyser.entity;
import javax.persistence.*;
#Entity(name = "users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
#Column(unique = true, nullable = false)
private String email;
private String dob;
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 String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
}
Then I have created UserRepository.java:
package ch.concertopro.webshopanalyser.repository;
import ch.concertopro.webshopanalyser.entity.User;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface UserRepository extends CrudRepository<User, Integer> {
}
And this is my service where I try to get the value of getName():
package ch.concertopro.webshopanalyser.service;
import ch.concertopro.webshopanalyser.entity.User;
import ch.concertopro.webshopanalyser.repository.UserRepository;
import org.springframework.stereotype.Service;
#Service
public class UserService {
final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public Iterable<User> getUser() {
return userRepository.findById(1).getName();
}
}
But I get the error Cannot resolve method 'getName' in 'Optional'. Why?
For your purpose you should change your method implementation like:
public Optional<String> getUser() {
return userRepository.findById(1)
.map(User::getName);
}
Hi everybody and thanks for helping me,
I'm trying to fetch data from an api url "https://api.stackexchange.com/2.2/search?order=desc&sort=creation&site=stackoverflow&tagged=android" and I don't know what I am missing.
I keep on getting an error saying that I am pointing to a null object, but it is not supposed to be null.
That is the error message
`
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.finalhomework, PID: 5005
java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Iterator java.util.List.iterator()' on a null object reference
at com.example.finalhomework.view.SearchActivity$1.onResponse(SearchActivity.java:46)
at retrofit2.DefaultCallAdapterFactory$ExecutorCallbackCall$1.lambda$onResponse$0$DefaultCallAdapterFactory$ExecutorCallbackCall$1(DefaultCallAdapterFactory.java:89)
at retrofit2.-$$Lambda$DefaultCallAdapterFactory$ExecutorCallbackCall$1$3wC8FyV4pyjrzrYL5U0mlYiviZw.run(lambda)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)`
That is the results page which is supposed to get all the item
`
package com.example.finalhomework.model;
import java.io.Serializable;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class StackOverflowPageResult implements Serializable
{
#SerializedName("StackOverflowItem")
#Expose
private List<StackOverflowItem> items = null;
#SerializedName("has_more")
#Expose
private Boolean hasMore;
#SerializedName("quota_max")
#Expose
private Integer quotaMax;
#SerializedName("quota_remaining")
#Expose
private Integer quotaRemaining;
private final static long serialVersionUID = -263378404000205617L;
public List<StackOverflowItem> getStackOverflowItem() {
return items;
}
public void setItems(List<StackOverflowItem> items) {
this.items = items;
}
public Boolean getHasMore() {
return hasMore;
}
public void setHasMore(Boolean hasMore) {
this.hasMore = hasMore;
}
public Integer getQuotaMax() {
return quotaMax;
}
public void setQuotaMax(Integer quotaMax) {
this.quotaMax = quotaMax;
}
public Integer getQuotaRemaining() {
return quotaRemaining;
}
public void setQuotaRemaining(Integer quotaRemaining) {
this.quotaRemaining = quotaRemaining;
}
}`
That is the Item itself:
`
package com.example.finalhomework.model;
import java.io.Serializable;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class StackOverflowItem implements Serializable
{
#SerializedName("tags")
#Expose
private List<String> tags = null;
#SerializedName("owner")
#Expose
private Owner owner;
#SerializedName("is_answered")
#Expose
private Boolean isAnswered;
#SerializedName("view_count")
#Expose
private Integer viewCount;
#SerializedName("answer_count")
#Expose
private Integer answerCount;
#SerializedName("score")
#Expose
private Integer score;
#SerializedName("last_activity_date")
#Expose
private Integer lastActivityDate;
#SerializedName("creation_date")
#Expose
private Integer creationDate;
#SerializedName("question_id")
#Expose
private Integer questionId;
#SerializedName("content_license")
#Expose
private String contentLicense;
#SerializedName("link")
#Expose
private String link;
#SerializedName("title")
#Expose
private String title;
#SerializedName("last_edit_date")
#Expose
private Integer lastEditDate;
#SerializedName("accepted_answer_id")
#Expose
private Integer acceptedAnswerId;
#SerializedName("closed_date")
#Expose
private Integer closedDate;
#SerializedName("closed_reason")
#Expose
private String closedReason;
private final static long serialVersionUID = 2088551364601451752L;
public List<String> getTags() {
return tags;
}
public void setTags(List<String> tags) {
this.tags = tags;
}
public Owner getOwner() {
return owner;
}
public void setOwner(Owner owner) {
this.owner = owner;
}
public Boolean getIsAnswered() {
return isAnswered;
}
public void setIsAnswered(Boolean isAnswered) {
this.isAnswered = isAnswered;
}
public Integer getViewCount() {
return viewCount;
}
public void setViewCount(Integer viewCount) {
this.viewCount = viewCount;
}
public Integer getAnswerCount() {
return answerCount;
}
public void setAnswerCount(Integer answerCount) {
this.answerCount = answerCount;
}
public Integer getScore() {
return score;
}
public void setScore(Integer score) {
this.score = score;
}
public Integer getLastActivityDate() {
return lastActivityDate;
}
public void setLastActivityDate(Integer lastActivityDate) {
this.lastActivityDate = lastActivityDate;
}
public Integer getCreationDate() {
return creationDate;
}
public void setCreationDate(Integer creationDate) {
this.creationDate = creationDate;
}
public Integer getQuestionId() {
return questionId;
}
public void setQuestionId(Integer questionId) {
this.questionId = questionId;
}
public String getContentLicense() {
return contentLicense;
}
public void setContentLicense(String contentLicense) {
this.contentLicense = contentLicense;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Integer getLastEditDate() {
return lastEditDate;
}
public void setLastEditDate(Integer lastEditDate) {
this.lastEditDate = lastEditDate;
}
public Integer getAcceptedAnswerId() {
return acceptedAnswerId;
}
public void setAcceptedAnswerId(Integer acceptedAnswerId) {
this.acceptedAnswerId = acceptedAnswerId;
}
public Integer getClosedDate() {
return closedDate;
}
public void setClosedDate(Integer closedDate) {
this.closedDate = closedDate;
}
public String getClosedReason() {
return closedReason;
}
public void setClosedReason(String closedReason) {
this.closedReason = closedReason;
}
}`
That is the Retrofit builder with the url:
`
package com.example.finalhomework.network;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class RetrofitInstance {
private static Retrofit retrofit;
private static final String BASE_URL ="https://api.stackexchange.com/2.2/";
public static Retrofit getRetrofitInstance(){
if (retrofit == null){
retrofit = new retrofit2.Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}`
That is the interface with the url's arguments:
`
package com.example.finalhomework.network;
import com.example.finalhomework.model.StackOverflowPageResult;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;
public interface GetStackOverflowItemDataService {
#GET("search")
Call<StackOverflowPageResult> getStackOverflowItem(
#Query("tagged") String tagged,
#Query("site") String site,
#Query("sort") String sort,
#Query("order") String order
);
}`
And here we've got the class which is supposed to get the total result, and I put a Log.i in order to check if everything is in order and the stackOverflowItems is null:
`
package com.example.finalhomework.view;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.os.Bundle;
import android.util.Log;
import com.example.finalhomework.R;
import com.example.finalhomework.model.StackOverflowItem;
import com.example.finalhomework.model.StackOverflowPageResult;
import com.example.finalhomework.network.GetStackOverflowItemDataService;
import com.example.finalhomework.network.RetrofitInstance;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class SearchActivity extends AppCompatActivity {
Toolbar toolbar;
private GetStackOverflowItemDataService stackOverflowItemDataService;
List<StackOverflowItem> stackOverflowItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
setToolbarBack();
stackOverflowItemDataService = RetrofitInstance.getRetrofitInstance().create(GetStackOverflowItemDataService.class);
stackOverflowItemDataService.getStackOverflowItem("android", "stackoverflow", "creation", "desc")
.enqueue(new Callback<StackOverflowPageResult>() {
#Override
public void onResponse(Call<StackOverflowPageResult> call, Response<StackOverflowPageResult> response) {
StackOverflowPageResult stackOverflowPageResult = response.body();
stackOverflowItems = stackOverflowPageResult.getStackOverflowItem();
for (StackOverflowItem s : stackOverflowItems) {
Log.i("Item StackOverflow :", s.getTitle());
}
}
#Override
public void onFailure(Call<StackOverflowPageResult> call, Throwable t) {
}
});
}`
Again thanks for the help
There is mismatch between JSON data variable and your #SerializedName("StackOverflowItem")
So make the changes to match the SerializedName, code as follows -
public class StackOverflowPageResult implements Serializable {
#SerializedName("items")
private List<StackOverflowItem> items;
#SerializedName("has_more")
private Boolean hasMore;
#SerializedName("quota_max")
private Integer quotaMax;
#SerializedName("quota_remaining")
private Integer quotaRemaining;
// your further code here
//.............
}
SerializedName is only required when you are going to take variable name different from JSON object, otherwise you can skip #SerializedName tag as well.
One more thing I suggest, I you are not going to call excludeFieldsWithoutExposeAnnotation() in your GsonBuilder class, then there is no need for #Expose tag.
The Gson #Expose annotation can be used to mark a field to be exposed or not (included or not) for serialized or deserialized. The #Expose annotation can take two parameters and each parameter is a boolean which can take either the value true or false. In order to get GSON to react to the #Expose annotations we must create a Gson instance using the GsonBuilder class and need to call the excludeFieldsWithoutExposeAnnotation() method, it configures Gson to exclude all fields from consideration for serialization or deserialization that do not have the Expose annotation.
Happy Coding !
Am new to Spring boot. Am trying to create an endpoint that will add vehicle under manager. I have two entites Vehicle and Manager and corresponding DTO are below. ManagerDTO has reference of VehicleDTO
VehicleDTO
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
import com.EngineType;
import com.Manufacturer;
#JsonDeserialize(builder = VehicleDTO.VehicleDTOBuilder.class)
#JsonInclude(JsonInclude.Include.NON_NULL)
public class VehicleDTO {
private Long vehicleid;
#NotNull(message = "vehcilenumber can not be null!")
#Size(min = 2, max = 14)
private String vehcilenumber;
#NotNull(message = "Engine Type can not be null!")
private EngineType enginetype;
#Min(1)
#Max(5)
private Integer rating;
private Manufacturer manufacturer;
private VehicleDTO(Long id, String vehcilenumber, EngineType enginetype,Integer rating,Manufacturer manufacturer){
this.vehcilenumber=vehcilenumber;
this.enginetype=enginetype;
this.rating=rating;
this.vehicleid=id;
this.manufacturer=manufacturer;
}
public static VehicleDTOBuilder newBuilder()
{
return new VehicleDTOBuilder();
}
public Long getvehicleid() {
return vehicleid;
}
public String getvehcilenumber() {
return vehcilenumber;
}
public EngineType getEnginetype() {
return enginetype;
}
public Integer getRating() {
return rating;
}
public Manufacturer getManufacture() {
return manufacturer;
}
#JsonPOJOBuilder(buildMethodName = "createVehicleDTO", withPrefix = "set")
public static class VehicleDTOBuilder{
private Long vehicleid;
private String vehcilenumber;
private EngineType enginetype;
private Integer rating;
private Manufacturer manufacturer;
public VehicleDTOBuilder setvehicleid(Long id) {
this.vehicleid = id;
return this;
}
public VehicleDTOBuilder setvehcilenumber(String vehcilenumber) {
this.vehcilenumber = vehcilenumber;
return this;
}
public VehicleDTOBuilder setEnginetype(EngineType enginetype) {
this.enginetype = enginetype;
return this;
}
public VehicleDTOBuilder setRating(Integer rating) {
this.rating = rating;
return this;
}
public VehicleDTOBuilder setManufacturer(Manufacturer manufacturer) {
this.manufacturer = manufacturer;
return this;
}
public VehicleDTO createVehicleDTO()
{
return new VehicleDTO(vehicleid, vehcilenumber, enginetype,rating,manufacturer);
}
}
}
And my ManagerDTO is below. This has reference of Vehcile DTO
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.VehicleDO;
import javax.validation.constraints.NotNull;
#JsonInclude(JsonInclude.Include.NON_NULL)
public class ManagerDTO {
#JsonIgnore
private Long id;
#NotNull(message = "Username can not be null!")
private String username;
#NotNull(message = "Password can not be null!")
private String password;
private VehicleDO vehicle;
private ManagerDTO() {
}
private ManagerDTO(Long id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
private ManagerDTO(Long id, String username, String password,VehicleDO vehicle) {
this.id = id;
this.username = username;
this.password = password;
this.vehicle = vehicle;
}
public static ManagerDTOBuilder newBuilder() {
return new ManagerDTOBuilder();
}
#JsonProperty
public Long getId() {
return id;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public VehicleDO getvehicle() {
return vehicle;
}
public static class ManagerDTOBuilder {
private Long id;
private String username;
private String password;
private VehicleDO vehicle;
public ManagerDTOBuilder setId(Long id) {
this.id = id;
return this;
}
public ManagerDTOBuilder setvehicle(VehicleDO vehicle) {
this.vehicle = vehicle;
return this;
}
public ManagerDTOBuilder setUsername(String username) {
this.username = username;
return this;
}
public ManagerDTOBuilder setPassword(String password) {
this.password = password;
return this;
}
public ManagerDTO createManagerDTO() {
return new ManagerDTO(id, username, password,vehicle);
}
}
}
And my controller is below
#PostMapping("/add")
public void mapVehicleAndManager(#Valid #RequestBody ManagerDTO managerDTO)
{
System.out.println("Print: "+managerDTO.getvehicle().getvehicleId());//this print null
}
So when my controller is called i can see username and password are populated where as vehicle is not populated. A not sure what am missing here and reason why jackson is not populating my java object.