Serializing Enum to JSON in Java - java

I have a Java enum where I store different statuses:
public enum BusinessCustomersStatus {
A("active", "Active"),
O("onboarding", "Onboarding"),
NV("not_verified", "Not Verified"),
V("verified", "Verified"),
S("suspended", "Suspended"),
I("inactive", "Inactive");
#Getter
private String shortName;
#JsonValue
#Getter
private String fullName;
BusinessCustomersStatus(String shortName, String fullName) {
this.shortName = shortName;
this.fullName = fullName;
}
// Use the fromStatus method as #JsonCreator
#JsonCreator
public static BusinessCustomersStatus fromStatus(String statusText) {
for (BusinessCustomersStatus status : values()) {
if (status.getShortName().equalsIgnoreCase(statusText)) {
return status;
}
}
throw new UnsupportedOperationException(String.format("Unknown status: '%s'", statusText));
}
}
Full code: https://github.com/rcbandit111/Search_specification_POC/blob/main/src/main/java/org/merchant/database/service/businesscustomers/BusinessCustomersStatus.java
The code works well when I want to get the list of items into pages for the value fullName because I use #JsonValue annotation.
I have a case where I need to get the shortValue for this code:
return businessCustomersService.findById(id).map( businessCustomers -> businessCustomersMapper.toFullDTO(businessCustomers));
Source: https://github.com/rcbandit111/Search_specification_POC/blob/316c97aa5dc34488771ee11fb0dcf6dc1e4303da/src/main/java/org/merchant/service/businesscustomers/BusinessCustomersRestServiceImpl.java#L77
But I get fullValue. Do you know for a single row how I can map the shortValue?

I'd recommend serializing it as an object. This can be done via the #JsonFormat annotation at the class level:
#JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum BusinessCustomersStatus {
A("active", "Active"),
O("onboarding", "Onboarding"),
//...
#Getter
private String shortName;
#Getter
private String fullName;
//...
This will lead to the following result when serializing this enum for BusinessCustomersStatus.A:
{"shortName":"active","fullName":"Active"}
Alternatively, you could define status field as String:
public class BusinessCustomersFullDTO {
private long id;
private String name;
private String businessType;
private String status;
}
and map its value like this:
businessCustomersFullDTO.status(businessCustomers.getStatus().getShortName());

Related

Field error in object 'titulo' on field 'status': rejected value [Pendente];

I am trying to learn Spring Framework on the go. During runtime I get following stacktrace:
Validation failed for object='title'. Error count: 1
org.springframework.validation.BindException:
org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'title' on field 'status': rejected value
[Received];
I noticed that the problem is in the status, which is formatted by enum, but I can't any error.
My class Controller:
#Controller
#RequestMapping("/titles")
public class registerTitleController {
#RequestMapping("/title")
public String new() {
return "RegisterTitle";
}
#Autowired
private Titles titles;
#RequestMapping(method=RequestMethod.POST)
public String saveIn(Title title) {
titles.save(title);
return "RegisterTitle";
}
}
My class entity
#Entity
public class Title {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long cod;
private String description;
#DateTimeFormat(pattern="dd/MM/yyyy")
#Temporal(TemporalType.DATE)
private Date dateV;
private BigDecimal val;
#Enumerated(value = EnumType.STRING)
private StatusTitle status;
//other accessor methods
My class enum
public enum StatusTitle {
PENDING("Pending"),
RECEIVED("Received");
private String description;
private StatusTitulo(String descricao){
this.description = description;
}
public String getDescription() {
return description;
}
}
My system work without the status of the attribute.
Can someone point out what is wrong? Your help will be much appreciated.
You probably are sending "Received", but you need to send "RECEIVED" string to properly convert to the ENUM by default.

Spring Boot enum JSON serializer

Below is the object that I want to convert to JSON;
public class TestDto{
private ResponseType responseType;
private Long id;
private String name;
}
The ResponseType below is an enum;
public enum ResponseType{
TEST1("test message 1"), TEST2("test message 2"), TEST3("test message 3");
private String message;
}
Below is the JSON which I want to create:
{"code":"TEST1", "message":"test message 1", "id":1, "name":"name"}
and code in the JSON response points the name of the enum and the message in the JSON response points the message field of the enum.
Is there any way to do it?
Easiest way to do this is to add derived getters/setters to TestDto, and suppress JSON serialization of the responseType field.
class TestDto {
private ResponseType responseType;
private Long id;
private String name;
#JsonIgnore // Suppress JSON serialization
public ResponseType getResponseType() {
return this.responseType;
}
public void setResponseType(ResponseType responseType) {
this.responseType = responseType;
}
public String getCode() { // Derived getter for "code" property
return this.responseType.name();
}
public void setCode(String code) { // Derived setter for "code" property
this.responseType = (code == null ? null : ResponseType.valueOf(code));
}
public String getMessage() { // Derived getter for "message" property
return this.responseType.getMessage();
}
#Deprecated // Shouldn't be called by Java code, since it's a dummy stub method
#SuppressWarnings("unused")
public void setMessage(String message) { // Derived setter for "message" property
// Ignore value
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
Two-way test
TestDto testDto = new TestDto();
testDto.setResponseType(ResponseType.TEST1);
testDto.setId(1L);
testDto.setName("name");
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(testDto);
System.out.println(json);
TestDto testDto2 = mapper.readValue(json, TestDto.class);
System.out.println(testDto2.getResponseType());
System.out.println(testDto2.getId());
System.out.println(testDto2.getName());
Output
{"id":1,"name":"name","message":"test message 1","code":"TEST1"}
TEST1
1
name
I have updated my previous answer as it wasn't correct. You can use #JsonFormat(shape = JsonFormat.Shape.OBJECT) to indicate that the enum should be serialized like an object (based on the getters).
#JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum ResponseType{
TEST1("test message 1"), TEST2("test message 2"), TEST3("test message 3");
private String message;
ResponseType(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public String getCode() {
return this.toString();
}
}
After that, you must also use #JsonUnwrapped on the Enum field to avoid having it's fields serialized as an object.
public static class TestDto {
#JsonUnwrapped private ResponseType responseType;
private Long id;
private String name;
}
Running the following code
TestDto testDto = new TestDto(ResponseType.TEST1, 1234356L, "First Response");
result = mapper.writeValueAsString(testDto);
System.out.println(result);
I get the result {"message":"test message 1","code":"TEST1","id":1234356,"name":"First Response"}

Java How to get collection(List) of specific values in JsonObject contains a JSONArray

I am new to Java and I have a javabeans conatins
class Players{
#SerializedName("status")
#Expose
private String status;
#SerializedName("teamOne")
#Expose
private List<TeamOne> teamOne;
#SerializedName("teamTwo")
#Expose
private List<TeamTwo> teamTwo;
public String getStatus() {return status);}
public void setStatus(String status) {this.status = status;}
public List<TeamOne> getTeamOne(){ return teamOne:}
public setTeamOne(List<TeamOne> teamOne){ this.teamOne= teamOne:}
public List<TeamTwo> getTeamTwo(){ return teamTwo:}
public setTeamTwo(List<TeamTwo> teamTwo){ this.teamTwo= teamTwo;}
}
class TeamOne {
#SerializedName("winningScore")
#Expose
private String winningScore;
#SerializedName("playerName")
#Expose
private String PlayerName;
}
class TeamTwo {
#SerializedName("winningScore")
#Expose
private String winningScore;
#SerializedName("playerName")
#Expose
private String PlayerName;
}
My json return looks like
{
"status":"BestPlayers",
"teamOne":[
{
"winningScore":"11",
"playerName":"John"
},
{
"winningScore":"11",
"playerName":"David"
}
],
"teamTwo":[
{
"winningScore":"15",
"playerName":"Victor"
},
{
"winningScore":"15",
"playerName":"Thomas"
}
]
}
Now I am trying to get List of the players Name in both teams.
which should look [John, David, Victor,Thomas]
I tried a while loop which could loop what ever the number on arrays but could not do that, but am getting only the first players name and thats it, I could not even reach to the second team array. I would really appreciate your help.
need help with this code
the problem is with your POJO Model class its should be TeamDetails or Team
class Players{
#SerializedName("status")
#Expose
private String status;
#SerializedName("teamOne")
#Expose
private List<Team> teamOne;
#SerializedName("teamTwo")
#Expose
private List<Team> teamTwo;
}
class Team {
#SerializedName("winningScore")
#Expose
private String winningScore;
#SerializedName("playerName")
#Expose
private String PlayerName;
}
now create a Final List of players like
private getTotalList(){
List<Team> finalTeams=new ArrayList()
if(null!=teamOne && teamOne.size()>0){ // thats how your requirment will work
finalTeams.add(teamOne)
}
//same goes for all teams add null check and add them.
if(null!=teamTwo && teamTwo .size()>0){ // thats how your requirment will work
finalTeams.add(teamTwo)
}
if(null!=funLovers && funLovers .size()>0){
finalTeams.add(funLovers)
}
return finalTeams:
}
then use foreach loop
for(Team team: finalTeams){
Log.d("playerName: ", team.PlayerName)
}

Jackson: deserialize with Builder along with standard setters/getters?

Is it possible with Jackson to deserialize json with Builder pattern as well as with default setter and getter approach?
My object is created with Builder that covers only required (final) fields, but I have non-final fields with some values as well that need to be deserialized with setters.
Here is the sample that throws an exception in an attempt to deserialize it with:
new ObjectMapper().readValue(json, Foo.class);
json - json representation serialized with default Jackson serializer, like:
objectMapper.writeValueAsString(foo);
class
#Getter
#Setter
#ToString
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonDeserialize(builder = Foo.Builder.class)
public class Foo {
private final String key;
private final Long user;
private final String action;
private final String material;
private final String currency;
private Foo(String key, Long user, String action, String material, String currency) {
this.key = key;
this.user = user;
this.action = action;
this.material = material;
this.currency = currency;
}
public static class Builder {
private String key;
private Long user;
private String action;
private String material;
private String currency;
#JsonProperty("key")
public Foo.Builder withKey(String key) {
this.key = key;
return this;
}
#JsonProperty("user")
public Foo.Builder withUser(Long user) {
this.user = user;
return this;
}
#JsonProperty("action")
public Foo.Builder withAction(String action) {
this.action = action;
return this;
}
/// other 'with' setters....
}
#JsonProperty("state")
private int state;
#JsonProperty("stat")
private String stat;
#JsonProperty("step")
private String step;
}
The exception it throws like :
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException:
Unrecognized field "state" (class com.Foo$Builder), not marked as
ignorable (5 known properties: "key", "user", "action", "material",
"currency",])
If not possible what workaround is the cheapest?
Two things that are suspicious:
You are willing to use the builder inside the Foo class. In that case you should correct the specification
(SessionData.Builder.class is not correct in that case).
You are indeed trying to use an external builder. In this case you should remove or at least mark as ignorable the inner builder, this seems to be the reason of the excetpion you are getting.
In both cases you should make sure the final method to get the Foo instance is called build() otherwise you should annotate the builder with a #JsonPOJOBuilder(buildMethodName = "nameOfMethod", withPrefix = "set").

Java object not populated from json request for inner class

Have searched in different sites but couldn't find correct answer, hence posting this request though it could possible duplicates.sorry for that.
I am sending the below json request to my back-end service and converting to java object for processing. I can see the request body passed to my service but when i convert from json to java object , values are not populating
{
"data":{
"username":"martin",
"customerId":1234567890,
"firstName":"john",
"lastName":"smith",
"password":"p#ssrr0rd##12",
"email":"john.smith#gmail.com",
"contactNumber":"0342323443",
"department":"sports",
"location":"texas",
"status":"unlocked",
"OrderConfigs":[
{
"vpnId":"N4234554R",
"serviceId":"connectNow",
"serviceType":"WRLIP",
"ipAddress":"10.101.10.3",
"fRoute":[
"10.255.253.0/30",
" 10.255.254.0/30"
],
"timeout":1800,
"mapId":"test_map"
}
]
}
}
My Parser class have something like,
JSONObject requestJSON = new JSONObject(requestBody).getJSONObject("data");
ObjectMapper mapper = new ObjectMapper();
final String jsonData = requestJSON.toString();
OrderDTO mappedObject= mapper.readValue(jsonData , OrderDTO .class);
// I can see value coming from front-end but not populating in the mappedObject
My OrderDTO.java
#JsonInclude(value = Include.NON_NULL)
#JsonIgnoreProperties(ignoreUnknown = true,value = {"hibernateLazyInitializer", "handler", "created"})
public class OrderDTO {
private String username;
private long customerId;
private String source;
private String firstName;
private String lastName;
private String email;
private String contactNumber;
private String password;
private String department;
private String location;
private String status;
private List<OrderConfig> OrderConfigs;
#JsonInclude(value = Include.NON_NULL)
public class OrderConfig {
private String vpnId;
private String serviceId;
private String serviceType;
private String ipAddress;
private String mapId;
private String[] fRoutes;
private Map<String, Object> attributes;
private SubConfig subConfig;
private String routeFlag;
getter/setters
.....
}
all setter/getter
}
Not sure what I'm missing here. Is this right way to do?
If your are trying to use inner class, correct way to use is to declare it static for Jackson to work with inner classes.
For reference check this
code changes made are
#JsonInclude(value = Include.NON_NULL)
#JsonIgnoreProperties(ignoreUnknown = true)
static class OrderConfig {
Make sure that your json tag names match with variable names of java object
Ex : "fRoute":[
"10.255.253.0/30",
" 10.255.254.0/30"
],
private String[] fRoutes;
OrderConfigs fields will not be initialized, just modify your bean as
#JsonProperty("OrderConfigs")
private List<OrderConfig> orderConfigs;
// setter and getter as setOrderConfigs / getOrderConfigs
See my answer here. (same issue)

Categories