JsonMappingException during Json unmarshal in Spring - java

This is my POJO class:
public class OrdineIngressi {
private Integer spettacolo;
private Integer settore;
private Integer pv;
private List<OrdineIngresso> ingressi=new ArrayList<OrdineIngresso>();
public OrdineIngressi(Integer spettacolo, Integer settore, Integer pv,
List<OrdineIngresso> ingressi) {
super();
this.spettacolo = spettacolo;
this.settore = settore;
this.pv = pv;
this.ingressi = ingressi;
}
public OrdineIngressi() {
super();
}
public Integer getSpettacolo() {
return spettacolo;
}
public void setSpettacolo(Integer spettacolo) {
this.spettacolo = spettacolo;
}
public Integer getSettore() {
return settore;
}
public void setSettore(Integer settore) {
this.settore = settore;
}
public Integer getPv() {
return pv;
}
public void setPv(Integer pv) {
this.pv = pv;
}
public List<OrdineIngresso> getIngressi() {
return ingressi;
}
public void setIngressi(List<OrdineIngresso> ingressi) {
this.ingressi = ingressi;
}
public class OrdineIngresso {
private Integer tipoingresso;
private Integer abbonamento;
private int numero;
private Integer[] posti;
public OrdineIngresso() {
super();
}
public OrdineIngresso(Integer tipoingresso, Integer abbonamento,
int numero, Integer[] posti) {
super();
this.tipoingresso = tipoingresso;
this.abbonamento = abbonamento;
this.numero = numero;
this.posti = posti;
}
public Integer getTipoingresso() {
return tipoingresso;
}
public void setTipoingresso(Integer tipoingresso) {
this.tipoingresso = tipoingresso;
}
public Integer getAbbonamento() {
return abbonamento;
}
public void setAbbonamento(Integer abbonamento) {
this.abbonamento = abbonamento;
}
public Integer[] getPosti() {
return posti;
}
public void setPosti(Integer[] posti) {
this.posti = posti;
}
public int getNumero() {
return numero;
}
public void setNumero(int numero) {
this.numero = numero;
}
}
}
This is the ajax input:
{"spettacolo":1,"settore":1,"pv":1,"ingressi":[{"tipoingresso":1,"abbonamento":null,"numero":1,"posti":[]}]}
When the Controller tries to unmarshal a json input I got this:
nested exception is org.codehaus.jackson.map.JsonMappingException: No suitable constructor found for type [simple type, class com.bean.OrdineIngressi$OrdineIngresso]: can not instantiate from JSON object (need to add/enable type information?)
Why? There is a default constructor!

You're almost there, you just need to make your inner class static:
...
public static class OrdineIngresso {
private Integer tipoingresso;
...
}
IIRC it has to do with the fact that a non-args inner class constructor really isn't non-args and thus jackson doesn't have a general manner for instantiating these non-static inner classes.
Cheers,

Related

Spring boot getting error on restTemplate.getForObject json parsing

I want to parse this json string but i am getting error, i tried with different way but it is not working
My error
Caused by: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of arrest_warrants out of START_ARRAY token
{
"arrest_warrants": [
{
"issuing_country_id": "CO",
"charge": "dfdfd",
"charge_translation": null
}
],
"weight": 0,
"forename": "MOISES",
"date_of_birth": "1965/06/02",
"entity_id": "2021/40054"
}
Parse calling: i am getting error on below line
Interpoldetails intterdt = restTemplate.getForObject("xxxurl"+id, Interpoldetails.class);
My class
#JsonIgnoreProperties(ignoreUnknown = true)
public class Interpoldetails {
private Integer weight;
private String date_of_birth;
private String entity_id;
private String name;
private arrest_warrants arrest_warrants;
private String[] languages_spoken_ids;
private Integer height;
private Integer sex_id;
private String country_of_birth_id;
private String place_of_birth;
public Integer getWeight() {
return weight;
}
public void setWeight(Integer weight) {
this.weight = weight;
}
public String getDate_of_birth() {
return date_of_birth;
}
public void setDate_of_birth(String date_of_birth) {
this.date_of_birth = date_of_birth;
}
public String getEntity_id() {
return entity_id;
}
public void setEntity_id(String entity_id) {
this.entity_id = entity_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String[] getLanguages_spoken_ids() {
return languages_spoken_ids;
}
public void setLanguages_spoken_ids(String[] languages_spoken_ids) {
this.languages_spoken_ids = languages_spoken_ids;
}
public Integer getHeight() {
return height;
}
public void setHeight(Integer height) {
this.height = height;
}
public Integer getSex_id() {
return sex_id;
}
public void setSex_id(Integer sex_id) {
this.sex_id = sex_id;
}
public String getCountry_of_birth_id() {
return country_of_birth_id;
}
public void setCountry_of_birth_id(String country_of_birth_id) {
this.country_of_birth_id = country_of_birth_id;
}
public String getPlace_of_birth() {
return place_of_birth;
}
public void setPlace_of_birth(String place_of_birth) {
this.place_of_birth = place_of_birth;
}
public arrest_warrants getArrest_warrants() {
return arrest_warrants;
}
public void setArrest_warrants(arrest_warrants arrest_warrants) {
this.arrest_warrants = arrest_warrants;
}
}
My inner class
#JsonIgnoreProperties(ignoreUnknown = true)
public class arrest_warrants {
private String issuing_country_id;
private String charge;
public String getIssuing_country_id() {
return issuing_country_id;
}
public void setIssuing_country_id(String issuing_country_id) {
this.issuing_country_id = issuing_country_id;
}
public String getCharge() {
return charge;
}
public void setCharge(String charge) {
this.charge = charge;
}
}
it should be arrest_warrants[] not String[]
As arrest_warrants is an array of objects you can create arrest_warrant object and in Interpoldetails class, use private List<arrest_warrant> arrest_warrants

Deserialize XML and get value using Java

When I use a distance API I get this response:
<?xml version="1.0" encoding="utf-8"?>
<Response xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/search/local/ws/rest/v1">
<Copyright>Copyright © 2020 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.</Copyright>
<BrandLogoUri>http://dev.virtualearth.net/Branding/logo_powered_by.png</BrandLogoUri>
<StatusCode>200</StatusCode>
<StatusDescription>OK</StatusDescription>
<AuthenticationResultCode>ValidCredentials</AuthenticationResultCode>
<TraceId>df8ee9b6422846f0b97644c0a631deb8|DU00000D71|0.0.0.0|DU000005EC, DU00000480|Ref A: F00DC0285E97417B99490A8C98E65E31 Ref B: DB3EDGE1608 Ref C: 2020-06-09T18:53:54Z|Ref A: 69E0F633DF6448A89B2B904773DF19AB Ref B: DB3EDGE0807 Ref C: 2020-06-09T18:53:54Z</TraceId>
<ResourceSets>
<ResourceSet>
<EstimatedTotal>1</EstimatedTotal>
<Resources>
<Route>
<Id>v69,h1509963868,i0,a2,cen-US,dAAAAAAAAAAA1,y0,s1,m1,o1,t4,wWriswmZmQkBa9bnail0kQA2~BFnWzEBwiKgBBH_gASHtAT8A0~VHVuaXMsIFR1bmlzaWE1~~~~v11,w-Ki_XmFfQUC94xQdyYUlQA2~BFnWzEBYRLoBBH_gAc1znT4B0~U2ZheCwgVHVuaXNpYQ2~~~~v11,k1</Id>
<BoundingBox>
<SouthLatitude>34.74499</SouthLatitude>
<WestLongitude>10.18235</WestLongitude>
<NorthLatitude>36.800014</NorthLatitude>
<EastLongitude>10.76493</EastLongitude>
</BoundingBox>
<DistanceUnit>Kilometer</DistanceUnit>
<DurationUnit>Second</DurationUnit>
<TravelDistance>271.101</TravelDistance>
...
I want to get the value of TravelDistance.
If possible a full code because I have been trying with this for long time and no solution.
You can use XmlMapper of jackson to de/serialize your XML.
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.9.8</version>
</dependency>
so you shall need to create an instance of it and deserialize as follows :
XmlMapper mapper = new XmlMapper();
Response value = xmlMapper.readValue("<Response>..</Response>", Response.class);
So you will need to create your object model that reflects your XML.
public class Response {
private String Copyright;
private String BrandLogoUri;
private String StatusCode;
private String StatusDescription;
private String AuthenticationResultCode;
private String TraceId;
ResourceSets ResourceSetsObject;
// Getter Methods
public String getCopyright() {
return Copyright;
}
public String getBrandLogoUri() {
return BrandLogoUri;
}
public String getStatusCode() {
return StatusCode;
}
public String getStatusDescription() {
return StatusDescription;
}
public String getAuthenticationResultCode() {
return AuthenticationResultCode;
}
public String getTraceId() {
return TraceId;
}
public ResourceSets getResourceSets() {
return ResourceSetsObject;
}
// Setter Methods
public void setCopyright(String Copyright) {
this.Copyright = Copyright;
}
public void setBrandLogoUri(String BrandLogoUri) {
this.BrandLogoUri = BrandLogoUri;
}
public void setStatusCode(String StatusCode) {
this.StatusCode = StatusCode;
}
public void setStatusDescription(String StatusDescription) {
this.StatusDescription = StatusDescription;
}
public void setAuthenticationResultCode(String AuthenticationResultCode) {
this.AuthenticationResultCode = AuthenticationResultCode;
}
public void setTraceId(String TraceId) {
this.TraceId = TraceId;
}
public void setResourceSets(ResourceSets ResourceSetsObject) {
this.ResourceSetsObject = ResourceSetsObject;
}
}
public class ResourceSets {
ResourceSet ResourceSetObject;
// Getter Methods
public ResourceSet getResourceSet() {
return ResourceSetObject;
}
// Setter Methods
public void setResourceSet(ResourceSet ResourceSetObject) {
this.ResourceSetObject = ResourceSetObject;
}
}
public class ResourceSet {
private String EstimatedTotal;
Resources ResourcesObject;
// Getter Methods
public String getEstimatedTotal() {
return EstimatedTotal;
}
public Resources getResources() {
return ResourcesObject;
}
// Setter Methods
public void setEstimatedTotal(String EstimatedTotal) {
this.EstimatedTotal = EstimatedTotal;
}
public void setResources(Resources ResourcesObject) {
this.ResourcesObject = ResourcesObject;
}
}
public class Resources {
Route RouteObject;
// Getter Methods
public Route getRoute() {
return RouteObject;
}
// Setter Methods
public void setRoute(Route RouteObject) {
this.RouteObject = RouteObject;
}
}
public class Route {
private String Id;
BoundingBox BoundingBoxObject;
private String DistanceUnit;
private String DurationUnit;
private String TravelDistance;
// Getter Methods
public String getId() {
return Id;
}
public BoundingBox getBoundingBox() {
return BoundingBoxObject;
}
public String getDistanceUnit() {
return DistanceUnit;
}
public String getDurationUnit() {
return DurationUnit;
}
public String getTravelDistance() {
return TravelDistance;
}
// Setter Methods
public void setId(String Id) {
this.Id = Id;
}
public void setBoundingBox(BoundingBox BoundingBoxObject) {
this.BoundingBoxObject = BoundingBoxObject;
}
public void setDistanceUnit(String DistanceUnit) {
this.DistanceUnit = DistanceUnit;
}
public void setDurationUnit(String DurationUnit) {
this.DurationUnit = DurationUnit;
}
public void setTravelDistance(String TravelDistance) {
this.TravelDistance = TravelDistance;
}
}
public class BoundingBox {
private String SouthLatitude;
private String WestLongitude;
private String NorthLatitude;
private String EastLongitude;
// Getter Methods
public String getSouthLatitude() {
return SouthLatitude;
}
public String getWestLongitude() {
return WestLongitude;
}
public String getNorthLatitude() {
return NorthLatitude;
}
public String getEastLongitude() {
return EastLongitude;
}
// Setter Methods
public void setSouthLatitude(String SouthLatitude) {
this.SouthLatitude = SouthLatitude;
}
public void setWestLongitude(String WestLongitude) {
this.WestLongitude = WestLongitude;
}
public void setNorthLatitude(String NorthLatitude) {
this.NorthLatitude = NorthLatitude;
}
public void setEastLongitude(String EastLongitude) {
this.EastLongitude = EastLongitude;
}
}

Parse Json with Gson in EnumClass

I have like this json.I'm using Gson to parse it and convert it in my custom class object.Here is a my java classes
public class ResponseModel {
private int resultCode;
private Match match;
public Match getMatch() {
return match;
}
public int getResultCode() {
return resultCode;
}
}
public class Match {
private Team team1;
private Team team2;
private double matchTime;
public Team getTeam1() {
return team1;
}
public Team getTeam2() {
return team2;
}
private Long matchDate;
private String stadiumAdress;
public double getMatchTime() {
return matchTime;
}
public Long getMatchDate() {
return matchDate;
}
public String getStadiumAdress() {
return stadiumAdress;
}
}
public class Team {
private String teamName;
private String teamImage;
public String getTeamName() {
return teamName;
}
public void setTeamName(String teamName) {
this.teamName = teamName;
}
public String getTeamImage() {
return teamImage;
}
public void setTeamImage(String teamImage) {
this.teamImage = teamImage;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public int getBallPosition() {
return ballPosition;
}
public void setBallPosition(int ballPosition) {
this.ballPosition = ballPosition;
}
private int score;
private int ballPosition;
}
I'm using Gson like this
ResponseModel responseModel = GsonUtil.fromJson(response.toString(), ResponseModel.class);
public class GsonUtil {
public static <T> T fromJson(String json, Class<T> c) {
return new Gson().fromJson(json, c);
}
public static String toJson(Object c) {
return new Gson().toJson(c);
}
}
Everything working perfect,I can convert my json to custom class.But I want to use enum class with team1 and team2. My goal is to convert like this enum class
MatchTeamType:
TEAM1 (1);
TEAM2 (2);
How I can rewrite my code with enum class?
Thanks

unique constraint Exception (SQLIntegrityConstraintViolationException)

I am trying to insert data in oracle DB using spring JPA repositories
I have a hash map which contains all the values which needs to be populated into DB,I am Iterating each value and setting into my Entity class
Basically I have a table which has a composite primary key(NotifiedToId).when I am setting the values ints throwing constraint violation exception.In my logs it is printing all correct values but its not getting inserted,
My Entity class:
#Embeddable
public class TbBamiNotifUserLogPK implements Serializable {
//default serial version id, required for serializable classes.
private static final long serialVersionUID = 1L;
#Column(name="NOTIF_REF_NO")
private String notifRefNo;
#Column(name="NOTIFIED_TO_ID")
private String notifiedToId;
public TbBamiNotifUserLogPK() {
}
public String getNotifRefNo() {
return this.notifRefNo;
}
public void setNotifRefNo(String notifRefNo) {
this.notifRefNo = notifRefNo;
}
public String getNotifiedToId() {
return this.notifiedToId;
}
public void setNotifiedToId(String notifiedToId) {
this.notifiedToId = notifiedToId;
}
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof TbBamiNotifUserLogPK)) {
return false;
}
TbBamiNotifUserLogPK castOther = (TbBamiNotifUserLogPK)other;
return
this.notifRefNo.equals(castOther.notifRefNo)
&& this.notifiedToId.equals(castOther.notifiedToId);
}
public int hashCode() {
final int prime = 31;
int hash = 17;
hash = hash * prime + this.notifRefNo.hashCode();
hash = hash * prime + this.notifiedToId.hashCode();
return hash;
}
}
import java.io.Serializable;
import javax.persistence.*;
#Entity
#Table(name="TB_BAMI_NOTIF_USER_LOG")
#NamedQuery(name="TbBamiNotifUserLog.findAll", query="SELECT t FROM TbBamiNotifUserLog t")
public class TbBamiNotifUserLog implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
private TbBamiNotifUserLogPK id;
#Column(name="NOTIF_CAT")
private String notifCat;
#Column(name="NOTIFIED_TO_NAME")
private String notifiedToName;
#Column(name="NOTIFIED_TO_ROLE")
private String notifiedToRole;
public TbBamiNotifUserLog() {
}
public TbBamiNotifUserLogPK getId() {
return this.id;
}
public void setId(TbBamiNotifUserLogPK id) {
this.id = id;
}
public String getNotifCat() {
return this.notifCat;
}
public void setNotifCat(String notifCat) {
this.notifCat = notifCat;
}
public String getNotifiedToName() {
return this.notifiedToName;
}
public void setNotifiedToName(String notifiedToName) {
this.notifiedToName = notifiedToName;
}
public String getNotifiedToRole() {
return this.notifiedToRole;
}
public void setNotifiedToRole(String notifiedToRole) {
this.notifiedToRole = notifiedToRole;
}
}
#Entity
#Table(name="TB_BAMI_NOTIFICATION_LOG")
#NamedQuery(name="TbBamiNotificationLog.findAll", query="SELECT t FROM TbBamiNotificationLog t")
public class TbBamiNotificationLog implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="NOTIF_REF_NO")
private String notifRefNo;
#Column(name="\"ACTION\"")
private String action;
#Column(name="NOTIF_CONTENT")
private String notifContent;
#Column(name="NOTIF_TYPE")
private String notifType;
#Column(name="NOTIFIED_DATE_TIME")
private Timestamp notifiedDateTime;
private String refno;
#Column(name="\"VERSION\"")
private BigDecimal version;
public TbBamiNotificationLog() {
}
public String getNotifRefNo() {
return this.notifRefNo;
}
public void setNotifRefNo(String notifRefNo) {
this.notifRefNo = notifRefNo;
}
public String getAction() {
return this.action;
}
public void setAction(String action) {
this.action = action;
}
public String getNotifContent() {
return this.notifContent;
}
public void setNotifContent(String notifContent) {
this.notifContent = notifContent;
}
public String getNotifType() {
return this.notifType;
}
public void setNotifType(String notifType) {
this.notifType = notifType;
}
public Timestamp getNotifiedDateTime() {
return this.notifiedDateTime;
}
public void setNotifiedDateTime(Timestamp notifiedDateTime) {
this.notifiedDateTime = notifiedDateTime;
}
public String getRefno() {
return this.refno;
}
public void setRefno(String refno) {
this.refno = refno;
}
public BigDecimal getVersion() {
return this.version;
}
public void setVersion(BigDecimal version) {
this.version = version;
}
}
Business Logic:
for (Entry<String, PushNotificationDetails> entry : finalTemplate.entrySet()){
try{
notificationlog.setNotifRefNo("121323");
notificationlog.setRefno(refNum);
notificationlog.setVersion(new BigDecimal(1));
notificationlog.setAction(action);
LOGGER.debug("TEMPLATE TYPE"+entry.getValue().getTemplate_type());
LOGGER.debug("TEMPLATE"+entry.getValue().getTemplate());
notificationlog.setNotifType(entry.getValue().getTemplate_type());
notificationlog.setNotifContent(entry.getValue().getTemplate());
notificationlog.setNotifiedDateTime(notifiedDateTime);
tbBamiNotifyLogRepository.save(notificationlog);
LOGGER.debug("inside if block ::: ");
LOGGER.debug("USERID is: "+entry.getValue().getUserID());
LOGGER.debug("NOTIFCAT is: "+entry.getValue().getNotif_cat());
LOGGER.debug("NOTIFUSER is: "+entry.getValue().getUserName());
LOGGER.debug("NOTIFROLE is: "+entry.getKey());
tbBamiNotifUserLogPK.setNotifiedToId(entry.getValue().getUserID());
tbBamiNotifUserLogPK.setNotifRefNo("121323");
tbBamiNotifUserLog.setId(tbBamiNotifUserLogPK);
LOGGER.debug("GET is: "+tbBamiNotifUserLog.getId().getNotifiedToId());
tbBamiNotifUserLog.setNotifCat(entry.getValue().getNotif_cat());
tbBamiNotifUserLog.setNotifiedToName(entry.getValue().getUserName());
tbBamiNotifUserLog.setNotifiedToRole(entry.getKey());
tbBamiNotifyUserLogRepository.save(tbBamiNotifUserLog);
}
Try to add notificationlog = new TbBamiNotificationLog() in the beginning of your saving for. It could be possible when you try to save the second row but the instance is the same (with id provided during the first save).

How to get an attribute/variable from a different class

I'm programming in a class and I need to have a variable from a different class. How can I do this?
package domein;
public class Speler
{
private String naam;
private String kleur;
private Sector sector;
private int Sector;
private int krediet = 10;
private int extraSchattingWaarde = 0;
private int nummer;
public Speler(String naam, String kleur, Sector sector)
{
setNaam(naam);
setKleur(kleur);
setSector(sector);
}
public String getNaam()
{
return this.naam;
}
public void setNaam(String naam)
{
//controle of het leeg is??
this.naam = naam;
}
public Sector getSector()
{
return this.sector;
}
private void setSector(Sector sector)
{
//tussen 1 en 4
this.sector = sector;
}
public String getKleur()
{
return this.kleur;
}
private void setKleur(String kleur)
{
//controle of het de beschikbare kleuren zijn
this.kleur = kleur;
}
public int getKrediet()
{
return this.krediet;
}
public void setKrediet(int krediet)
{
this.krediet = krediet;
}
public int getExtraSchattingWaarde()
{
return this.extraSchattingWaarde;
}
public void setExtraSchattingWaarde(int waarde)
{
this.extraSchattingWaarde = waarde;
}
}
This is the class where I need to get the variables and some methods. How can I make this class global?
Just a thing : this line is wrong private int Sector; because you can not use a class name as your variable name. This should hide your class visibility.
I assume this is an error and I continue the explanation.
In an other class you can instanciate this class and call the values. For example:
public class MyClass {
private Speler mySpeler = new Speler("AAA", "BBB", 3);
public MyClass() {}
public void myMethod() {
System.out.println(mySpeler.getKleur());
}
}

Categories

Resources