ObjectMapper Class Construction - java
I have big chunk of data, that I'd like to make it an object in java (E.g. https://haste.razvancode.com/agiyamuyol.json)
I'm running this code:
ObjectMapper mapper = new ObjectMapper();
File f = new File("example.json");
if (!f.exists()) f.createNewFile();
Board board = mapper.readValue(f, Board.class);
System.out.println(board.getName());
and I get this error:
Exception in thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "isTemplate" (class com.razvancode.discordbot.Utils.Board$Prefs), not marked as ignorable (21 known properties: "calendarFeedEnabled", "voting", "backgroundBottomColor", "cardAging", "backgroundImage", "background", "canBePrivate", "canBeOrg", "comments", "permissionLevel", "selfJoin", "canInvite", "invitations", "backgroundTopColor", "backgroundBrightness", "hideVotes", "cardCovers", "canBeEnterprise", "backgroundTile", "canBePublic", "backgroundImageScaled"])
at [Source: (File); line: 35, column: 23] (through reference chain: com.razvancode.discordbot.Utils.Board["prefs"]->com.razvancode.discordbot.Utils.Board$Prefs["isTemplate"])
at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:61)
at com.fasterxml.jackson.databind.DeserializationContext.handleUnknownProperty(DeserializationContext.java:823)
at com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:1153)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownProperty(BeanDeserializerBase.java:1589)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownVanilla(BeanDeserializerBase.java:1567)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:258)
at com.fasterxml.jackson.databind.deser.impl.InnerClassProperty.deserializeAndSet(InnerClassProperty.java:90)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:288)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:151)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4013)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2902)
at com.razvancode.discordbot.Test.<init>(Test.java:28)
at com.razvancode.discordbot.Test.main(Test.java:34)
Process finished with exit code 1
I'm 100% sure that is from my Board class, but I'm working for hours now and I still can't get it to work.
Boardclass:
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import java.util.ArrayList;
#NoArgsConstructor
#AllArgsConstructor
public class Board {
#Getter
private Object descData, pinned, datePluginDisable, idBoardSource, limits, templateGallery, ixUpdate, idEnterprise, idMemberCreator;
#Getter
private String shortUrl, dateLastActivity, shortLink, creationMethod, idOrganization, dateLastView, id, url, name, desc;
#Getter
private boolean subscribed, starred, enterpriseOwned, closed;
#Getter
private ArrayList<Memberships> memberships;
#Getter
private ArrayList<String> idTags, powerUps, premiumFeatures;
#Getter
private LabelNames labelNames;
#Getter
private Prefs prefs;
#NoArgsConstructor
#AllArgsConstructor
public static class LabelNames {
#Getter
private String orange, red, sky, pink, green, blue, lime, yellow, black, purple;
}
#NoArgsConstructor
#AllArgsConstructor
public static class Prefs {
#Getter
private String backgroundBrightness, comments, backgroundTopColor, backgroundImage, backgroundBottomColor, voting, permissionLevel, cardAging, invitations, background;
#Getter
private boolean canBeEnterprise, hideVotes, canBeOrg, calendarFeedEnabled, backgroundTile, canBePublic, canBePrivate, canInvite, isTemplate, cardCovers, selfJoin;
#Getter
private ArrayList<BackgroundImageScaled> backgroundImageScaled;
}
#NoArgsConstructor
#AllArgsConstructor
public static class BackgroundImageScaled {
#Getter
private String url;
#Getter
private Long width, height;
}
#NoArgsConstructor
#AllArgsConstructor
public static class Memberships {
#Getter
private String idMember, id, memberType;
#Getter
private boolean unconfirmed, deactivated;
}
}
If you have any ideas on how can I fix it, or where I was wrong please tell me.
It might be related to this answer. You might need to stop lombok from generating the getter as isTemplate() rather than isIsTemplate(), given that jackson will assume the boolean field in the data is called template.
Related
How can I use JAXB to bind mulitple non-unique elements
I'm having this issue with parsing XML using JAXB. Here is a simplified layout of the XML in question: <message> <header> <network>NET</network> <sendTime>0722</sendTime> </header> <generalInformation> <senderReference>1234</senderReference> <linkage> <externalReference>extRef</externalReference> </linkage> <linkage> <internalReference>intRef</internalReference> </linkage> <linkage> <systemReference>sysRef</externalReference> </linkage> </generalInformation> </message> The problem I'm having is that these references are being sent under the linkage tag which is not unique, and also doesn't have a root like "linkages" which would allow me to easily wrap it in a list in Java, because the generalInformation tag has other tags in it. Here is how I have it set up so far: #XmlRootElement(name="message") #NoArgsConstructor #AllArgsConstructor #Data public class Message { private Header header; private GeneralInformation generalInformation; } #XmlRootElement(name="header") #NoArgsConstructor #AllArgsConstructor #Data public class Header { private String network; private String sendTime; } #XmlRootElement(name="generalInformation") #NoArgsConstructor #AllArgsConstructor #Data public class GeneralInformation { private String senderReference; //How to create for linkages?? } So my question to you is, how can I configure the GeneralInformation class to handle these multiple linkages? I am mostly concerned with unmarshalling from XML to Java at the moment.
Just define it as a List, for example: private List<Linkage> linkage; and define the Linkage class to have single String property: #XmlRootElement(name="linkage") ... public class Linkage { private String systemReference; }
#XmlRootElement(name="generalInformation") #NoArgsConstructor #AllArgsConstructor #Data public class GeneralInformation { private String senderReference; private List<Linkage>; } #XmlRootElement(name="linkage") #NoArgsConstructor #AllArgsConstructor #Data public class Linkage { private String externalReference; private String internalReference; private String systemReference; }
Default boolean setting in DTO
I want to define default false for boolean but it seems still true as default on swagger. How could I define this to see false as default. Swagger request : { "transferList": [ { "reverseFlag": true, "transactionId": 0 } ] } Dto class #Getter #Setter #Builder #NoArgsConstructor #AllArgsConstructor public class TransferDto { private Long transactionId; private Boolean reverseFlag = false; }
This way is not enough. You can try this: #Getter #Setter #Builder #NoArgsConstructor #AllArgsConstructor public class TransferDto { private Long transactionId; #Builder.Default private Boolean reverseFlag = false; }
Does #AllArgsConstructor create constructor for static member?
For this class will #AllArgsConstructor create field for count? #Data #NoArgsConstructor #AllArgsConstructor public class Money { private int paisa; private int rs; private static int count; }
No, it will not. See here: https://projectlombok.org/features/constructor Static fields are skipped by these annotations.
Why #Data and #Builder doesnt work together
I have this simple class public class ErrorDetails { private String param = null; private String moreInfo = null; private String reason = null; ... } After refactoring, I added #Data and #Builder, but all the instantiations doesn't work any more ErrorDetails errorDetails = new ErrorDetails(); 'ErrorDetails(java.lang.String, java.lang.String, java.lang.String)' is not public in 'com.nordea.openbanking.payments.common.ndf.client.model.error.ErrorDetails'. Cannot be accessed from outside package If I removed #Builder, then it will work fine, Why I cannot use #Data and #Builder together?
Lombok's #Builder must have #AllArgsConstructor in order to work Adding also #AllArgsConstructor should do Under the hood it build all fields using constructor with all fields applying #Builder to a class is as if you added #AllArgsConstructor(access = AccessLevel.PACKAGE) to the class and applied the #Builder annotation to this all-args-constructor. This only works if you haven't written any explicit constructors yourself.
The full config should be : #Data #Builder(toBuilder = true) #AllArgsConstructor #NoArgsConstructor class ErrorDetails { private String param; // no need to initiate with null private String moreInfo; private String reason; }
Jackson2 and Lombok #Builder
Given I have the POJO: import lombok.Builder; import lombok.Data; #Data #Builder public class SomeResponse { private String author; private String authorTitle; private String teaser; private String text; private Long lastModified; private Long created; private Integer rating; private Optional<Markdown> markdown; private Optional<Integer> wordCount; } When I try to use the POJO in such normal Jackson construction: restTemplate.getForObject(urlTemplate, SomeResponse.class, productId.toString(), siteId.toString()); I get an exception, because there are private ctor in the SomeResponse class due to Lombok #Builder annotation. How can I make it works without deleting Lombok #Builder annotation?
Also add #AllArgsConstructor and #NoArgsConstructor, possible with the right access values. See the documentation for appropriate parameters. Disclosure: I am a lombok developer.