jaxb returning null vaue after unmarshal - java

I am trying to Unmarshall a xml and it is returning null value
XML:
<letterOutHeader>
<lettertype>
MN13
</lettertype>
<letterReqid>
9294678
</letterReqid>
<language>
en
</language>
<attentionTo></attentionTo>
<addressLine1></addressLine1>
<addressLine2></addressLine2>
<city>Case City</city>
<state>NY</state>
<zipCode>59559</zipCode>
<dateOfLetter>12/28/2016</dateOfLetter>
<respondByDate/>
<externalNum>Ac0287356894754</externalNum>
<letterOutFlexField>
<name>fieldOne </name>
<value>valueOne</value>
</letterOutFlexField>
<letterOutFlexField>
<name>fieldTwo</name>
<value>valueTwo</value>
</letterOutFlexField>
<letterOutFlexField>
<name>fieldThree</name>
<value>valueThree</value>
</letterOutFlexField>
<letterOutFlexField>
<name>fieldFour</name>
<value>valueFour</value>
</letterOutFlexField>
</letterOutHeader>
Bean:
package jaxb.Bean;
import java.util.List;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class LetterOutHeader {
String lettertype;
String letterReqid;
String language;
String attentionTo;
String addressLine1;
String addressLine2;
String city;
String state;
String zipCode;
String dateOfLetter;
String respondByDate;
String externalNum;
List<LetterOutFlexFieldBean> flexFields;
#XmlAttribute
public String getLettertype() {
return lettertype;
}
public void setLettertype(String lettertype) {
this.lettertype = lettertype;
}
#XmlAttribute
public String getLetterReqid() {
return letterReqid;
}
public void setLetterReqid(String letterReqid) {
this.letterReqid = letterReqid;
}
#XmlAttribute
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
#XmlAttribute
public String getAttentionTo() {
return attentionTo;
}
public void setAttentionTo(String attentionTo) {
this.attentionTo = attentionTo;
}
#XmlAttribute
public String getAddressLine1() {
return addressLine1;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
#XmlAttribute
public String getAddressLine2() {
return addressLine2;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
#XmlAttribute
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
#XmlAttribute
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
#XmlAttribute
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
#XmlAttribute
public String getDateOfLetter() {
return dateOfLetter;
}
public void setDateOfLetter(String dateOfLetter) {
this.dateOfLetter = dateOfLetter;
}
#XmlAttribute
public String getRespondByDate() {
return respondByDate;
}
public void setRespondByDate(String respondByDate) {
this.respondByDate = respondByDate;
}
#XmlAttribute
public String getExternalNum() {
return externalNum;
}
public void setExternalNum(String externalNum) {
this.externalNum = externalNum;
}
#XmlElement
public List<LetterOutFlexFieldBean> getFlexFields() {
return flexFields;
}
public void setFlexFields(List<LetterOutFlexFieldBean> flexFields) {
this.flexFields = flexFields;
}
}
UnMarshaling :
package jaxb.client;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import jaxb.Bean.LetterOutBean;
import jaxb.Bean.LetterOutHeader;
public class XmlToObject {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
File file = new File("C:/Users/sindhu/Desktop/Kranthi/jaxB/baseXML.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(LetterOutHeader.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
LetterOutHeader que= (LetterOutHeader) jaxbUnmarshaller.unmarshal(file);
System.out.println(que.getCity());
/* System.out.println("Answers:");
List<Answer> list=que.getAnswers();
for(Answer ans:list)
System.out.println(ans.getId()+" "+ans.getAnswername()+" "+ans.getPostedby());
*/
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
I have looked into the below posts in order to avoid duplicate question
JAXB unmarshal returning null values
JAXB unmarshalling returning Null

There are many mismatch between your provided XML and JAXB class.
Firstly, there are no attributes in your sample XML, but the JAXB contains #XmlAttribute.
Secondly, it is better to declare the #XmlAccessorType explicitly or otherwise it looks for only public fields and methods.
LetterOutHeader.java
package int1.d3;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name="letterOutHeader")
#XmlAccessorType(XmlAccessType.FIELD)
public class LetterOutHeader {
String lettertype;
String letterReqid;
String language;
String attentionTo;
String addressLine1;
String addressLine2;
String city;
String state;
String zipCode;
String dateOfLetter;
String respondByDate;
String externalNum;
#XmlElement(name="letterOutFlexField")
List<LetterOutFlexFieldBean> flexField;
public String getLettertype() {
return lettertype;
}
public void setLettertype(String lettertype) {
this.lettertype = lettertype;
}
public String getLetterReqid() {
return letterReqid;
}
public void setLetterReqid(String letterReqid) {
this.letterReqid = letterReqid;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
public String getAttentionTo() {
return attentionTo;
}
public void setAttentionTo(String attentionTo) {
this.attentionTo = attentionTo;
}
public String getAddressLine1() {
return addressLine1;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public String getAddressLine2() {
return addressLine2;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
public String getDateOfLetter() {
return dateOfLetter;
}
public void setDateOfLetter(String dateOfLetter) {
this.dateOfLetter = dateOfLetter;
}
public String getRespondByDate() {
return respondByDate;
}
public void setRespondByDate(String respondByDate) {
this.respondByDate = respondByDate;
}
public String getExternalNum() {
return externalNum;
}
public void setExternalNum(String externalNum) {
this.externalNum = externalNum;
}
public List<LetterOutFlexFieldBean> getFlexFields() {
if(flexField == null) {
flexField = new ArrayList<LetterOutFlexFieldBean>();
}
return this.flexField;
}
}

Related

How to Fetch data from API using Retrofit in Android

I'm Trying to call API using retrofit in Android. Although I'm successfully able to api in response I'm getting Success Code = 200. But Apart from that Inside Json object Json array is null although while I'm trying to call same api in Postman I'm getting the desire result.
I'm trying to call using POST request
URL Request :- https://example.com/AD1/api/user/profile
I'm passing parameter in Body userid:- MFL176116
Below Postman
APIInterface.java
public interface APIInterface {
#POST("profile")
Call<ProfilePojo> getUserProfile(#Body ProfilePojo profilePojo);
}
ProfilePojo.java
public class ProfilePojo {
#SerializedName("message")
#Expose
private String message;
#SerializedName("code")
#Expose
private Integer code;
#SerializedName("user_data")
#Expose
private List<UserDatum> userData = new ArrayList();
private String userid;
public ProfilePojo(String userid) {
this.userid = userid;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<UserDatum> getUserData() {
return userData;
}
public void setUserData(List<UserDatum> userData) {
this.userData = userData;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public class UserDatum {
#SerializedName("id")
#Expose
private String id;
#SerializedName("username")
#Expose
private String username;
#SerializedName("password")
#Expose
private String password;
#SerializedName("under_id")
#Expose
private String underId;
#SerializedName("place_under_id")
#Expose
private String placeUnderId;
#SerializedName("mobile")
#Expose
private String mobile;
#SerializedName("side")
#Expose
private String side;
#SerializedName("email")
#Expose
private String email;
#SerializedName("status")
#Expose
private String status;
#SerializedName("member_name")
#Expose
private String memberName;
#SerializedName("package_id")
#Expose
private String packageId;
#SerializedName("package_id1")
#Expose
private String packageId1;
#SerializedName("avatar")
#Expose
private String avatar;
#SerializedName("gender")
#Expose
private Object gender;
#SerializedName("date_of_birth")
#Expose
private Object dateOfBirth;
#SerializedName("address_line1")
#Expose
private String addressLine1;
#SerializedName("address_line2")
#Expose
private String addressLine2;
#SerializedName("country")
#Expose
private String country;
#SerializedName("country_code")
#Expose
private String countryCode;
#SerializedName("state")
#Expose
private String state;
#SerializedName("city")
#Expose
private String city;
#SerializedName("pincode")
#Expose
private String pincode;
#SerializedName("pancard_no")
#Expose
private String pancardNo;
#SerializedName("adharcard_no")
#Expose
private String adharcardNo;
#SerializedName("franchaise_type")
#Expose
private String franchaiseType;
#SerializedName("franchise_id")
#Expose
private Object franchiseId;
#SerializedName("franchise_per")
#Expose
private Object franchisePer;
#SerializedName("franchise_status")
#Expose
private Object franchiseStatus;
#SerializedName("transaction_pass")
#Expose
private String transactionPass;
#SerializedName("id_proof")
#Expose
private Object idProof;
#SerializedName("address_proof")
#Expose
private Object addressProof;
#SerializedName("self_video")
#Expose
private String selfVideo;
#SerializedName("residential_proof")
#Expose
private String residentialProof;
#SerializedName("btc_address")
#Expose
private Object btcAddress;
#SerializedName("perfect_money")
#Expose
private Object perfectMoney;
#SerializedName("email_status")
#Expose
private String emailStatus;
#SerializedName("email_verify")
#Expose
private String emailVerify;
#SerializedName("created_on")
#Expose
private String createdOn;
#SerializedName("edited_on")
#Expose
private String editedOn;
#SerializedName("isDeleted")
#Expose
private String isDeleted;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUnderId() {
return underId;
}
public void setUnderId(String underId) {
this.underId = underId;
}
public String getPlaceUnderId() {
return placeUnderId;
}
public void setPlaceUnderId(String placeUnderId) {
this.placeUnderId = placeUnderId;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getSide() {
return side;
}
public void setSide(String side) {
this.side = side;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMemberName() {
return memberName;
}
public void setMemberName(String memberName) {
this.memberName = memberName;
}
public String getPackageId() {
return packageId;
}
public void setPackageId(String packageId) {
this.packageId = packageId;
}
public String getPackageId1() {
return packageId1;
}
public void setPackageId1(String packageId1) {
this.packageId1 = packageId1;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public Object getGender() {
return gender;
}
public void setGender(Object gender) {
this.gender = gender;
}
public Object getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Object dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getAddressLine1() {
return addressLine1;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public String getAddressLine2() {
return addressLine2;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCountryCode() {
return countryCode;
}
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getPincode() {
return pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
public String getPancardNo() {
return pancardNo;
}
public void setPancardNo(String pancardNo) {
this.pancardNo = pancardNo;
}
public String getAdharcardNo() {
return adharcardNo;
}
public void setAdharcardNo(String adharcardNo) {
this.adharcardNo = adharcardNo;
}
public String getFranchaiseType() {
return franchaiseType;
}
public void setFranchaiseType(String franchaiseType) {
this.franchaiseType = franchaiseType;
}
public Object getFranchiseId() {
return franchiseId;
}
public void setFranchiseId(Object franchiseId) {
this.franchiseId = franchiseId;
}
public Object getFranchisePer() {
return franchisePer;
}
public void setFranchisePer(Object franchisePer) {
this.franchisePer = franchisePer;
}
public Object getFranchiseStatus() {
return franchiseStatus;
}
public void setFranchiseStatus(Object franchiseStatus) {
this.franchiseStatus = franchiseStatus;
}
public String getTransactionPass() {
return transactionPass;
}
public void setTransactionPass(String transactionPass) {
this.transactionPass = transactionPass;
}
public Object getIdProof() {
return idProof;
}
public void setIdProof(Object idProof) {
this.idProof = idProof;
}
public Object getAddressProof() {
return addressProof;
}
public void setAddressProof(Object addressProof) {
this.addressProof = addressProof;
}
public String getSelfVideo() {
return selfVideo;
}
public void setSelfVideo(String selfVideo) {
this.selfVideo = selfVideo;
}
public String getResidentialProof() {
return residentialProof;
}
public void setResidentialProof(String residentialProof) {
this.residentialProof = residentialProof;
}
public Object getBtcAddress() {
return btcAddress;
}
public void setBtcAddress(Object btcAddress) {
this.btcAddress = btcAddress;
}
public Object getPerfectMoney() {
return perfectMoney;
}
public void setPerfectMoney(Object perfectMoney) {
this.perfectMoney = perfectMoney;
}
public String getEmailStatus() {
return emailStatus;
}
public void setEmailStatus(String emailStatus) {
this.emailStatus = emailStatus;
}
public String getEmailVerify() {
return emailVerify;
}
public void setEmailVerify(String emailVerify) {
this.emailVerify = emailVerify;
}
public String getCreatedOn() {
return createdOn;
}
public void setCreatedOn(String createdOn) {
this.createdOn = createdOn;
}
public String getEditedOn() {
return editedOn;
}
public void setEditedOn(String editedOn) {
this.editedOn = editedOn;
}
public String getIsDeleted() {
return isDeleted;
}
public void setIsDeleted(String isDeleted) {
this.isDeleted = isDeleted;
}
}
}
Dashboard.java
private void getUserProfile() {
apiInterface = ApiLinks.getClient().create(APIInterface.class);
ProfilePojo profilePojo = new ProfilePojo("MFL176116");
Call<ProfilePojo> call = apiInterface.getUserProfile(profilePojo);
call.enqueue(new Callback<ProfilePojo>() {
#Override
public void onResponse(#NonNull Call<ProfilePojo> call, #NonNull Response<ProfilePojo> response) {
ProfilePojo profilePojo = response.body();
Toast.makeText(getApplicationContext(), "sucess", Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(#NonNull Call<ProfilePojo> call, #NonNull Throwable t) {
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
After debugging the code can see Message is success, code =200, but userdata size ==0 please help me to get rid of this error
Check again the way that you are calling the api, even your userid is getting null, probably it's getting null in the user, but the response is 200 bc there was no error, simply no user with that id.

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `response` out of START_ARRAY token

I keep getting this response when im trying to execute my retrofit call for this reseponse:
package retrofit.responses;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"id",
"version",
"createdDate",
"modifiedDate",
"rie",
"line1",
"line2",
"line3",
"line4",
"line5",
"county",
"postCode",
"country",
"primary",
"accomodationStatus",
"addressType",
"effectiveFrom",
"effectiveTo",
"secured"
})
#Generated("jsonschema2pojo")
public class ReferralResponse {
#JsonProperty("id")
private Object id;
#JsonProperty("version")
private Integer version;
#JsonProperty("createdDate")
private Object createdDate;
#JsonProperty("modifiedDate")
private Object modifiedDate;
#JsonProperty("rie")
private Boolean rie;
#JsonProperty("line1")
private String line1;
#JsonProperty("line2")
private Object line2;
#JsonProperty("line3")
private Object line3;
#JsonProperty("line4")
private String line4;
#JsonProperty("line5")
private Object line5;
#JsonProperty("county")
private Object county;
#JsonProperty("postCode")
private String postCode;
#JsonProperty("country")
private Object country;
#JsonProperty("primary")
private Boolean primary;
#JsonProperty("accomodationStatus")
private AccomodationStatus accomodationStatus;
#JsonProperty("addressType")
private Object addressType;
#JsonProperty("effectiveFrom")
private Long effectiveFrom;
#JsonProperty("effectiveTo")
private Object effectiveTo;
#JsonProperty("secured")
private Boolean secured;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("id")
public Object getId() {
return id;
}
#JsonProperty("id")
public void setId(Object id) {
this.id = id;
}
#JsonProperty("version")
public Integer getVersion() {
return version;
}
#JsonProperty("version")
public void setVersion(Integer version) {
this.version = version;
}
#JsonProperty("createdDate")
public Object getCreatedDate() {
return createdDate;
}
#JsonProperty("createdDate")
public void setCreatedDate(Object createdDate) {
this.createdDate = createdDate;
}
#JsonProperty("modifiedDate")
public Object getModifiedDate() {
return modifiedDate;
}
#JsonProperty("modifiedDate")
public void setModifiedDate(Object modifiedDate) {
this.modifiedDate = modifiedDate;
}
#JsonProperty("rie")
public Boolean getRie() {
return rie;
}
#JsonProperty("rie")
public void setRie(Boolean rie) {
this.rie = rie;
}
#JsonProperty("line1")
public String getLine1() {
return line1;
}
#JsonProperty("line1")
public void setLine1(String line1) {
this.line1 = line1;
}
#JsonProperty("line2")
public Object getLine2() {
return line2;
}
#JsonProperty("line2")
public void setLine2(Object line2) {
this.line2 = line2;
}
#JsonProperty("line3")
public Object getLine3() {
return line3;
}
#JsonProperty("line3")
public void setLine3(Object line3) {
this.line3 = line3;
}
#JsonProperty("line4")
public String getLine4() {
return line4;
}
#JsonProperty("line4")
public void setLine4(String line4) {
this.line4 = line4;
}
#JsonProperty("line5")
public Object getLine5() {
return line5;
}
#JsonProperty("line5")
public void setLine5(Object line5) {
this.line5 = line5;
}
#JsonProperty("county")
public Object getCounty() {
return county;
}
#JsonProperty("county")
public void setCounty(Object county) {
this.county = county;
}
#JsonProperty("postCode")
public String getPostCode() {
return postCode;
}
#JsonProperty("postCode")
public void setPostCode(String postCode) {
this.postCode = postCode;
}
#JsonProperty("country")
public Object getCountry() {
return country;
}
#JsonProperty("country")
public void setCountry(Object country) {
this.country = country;
}
#JsonProperty("primary")
public Boolean getPrimary() {
return primary;
}
#JsonProperty("primary")
public void setPrimary(Boolean primary) {
this.primary = primary;
}
#JsonProperty("accomodationStatus")
public AccomodationStatus getAccomodationStatus() {
return accomodationStatus;
}
#JsonProperty("accomodationStatus")
public void setAccomodationStatus(AccomodationStatus accomodationStatus) {
this.accomodationStatus = accomodationStatus;
}
#JsonProperty("addressType")
public Object getAddressType() {
return addressType;
}
#JsonProperty("addressType")
public void setAddressType(Object addressType) {
this.addressType = addressType;
}
#JsonProperty("effectiveFrom")
public Long getEffectiveFrom() {
return effectiveFrom;
}
#JsonProperty("effectiveFrom")
public void setEffectiveFrom(Long effectiveFrom) {
this.effectiveFrom = effectiveFrom;
}
#JsonProperty("effectiveTo")
public Object getEffectiveTo() {
return effectiveTo;
}
#JsonProperty("effectiveTo")
public void setEffectiveTo(Object effectiveTo) {
this.effectiveTo = effectiveTo;
}
#JsonProperty("secured")
public Boolean getSecured() {
return secured;
}
#JsonProperty("secured")
public void setSecured(Boolean secured) {
this.secured = secured;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
and im trying to getID and use that in another call. This is an object that I am trying to turn into an integer an then use that in a seperate call again.
referralResponseResponse = call1.getReferral(token).execute();
int i = (int) referralResponseResponse.body().getId();
System.out.println("Int: " + i);
I should also note the json that I'm using this data from is very large so ive just used jsonpogo to extract this information to a java file and then use the parts that apply to me, I dont imagine i have to set up a java class for every part of the retruned json
Try to add following annotation for your POJO class:
#JsonIgnoreProperties(ignoreUnknown = true)

Iterating through the results of the JSON response - Android + Retrofit + Moshi

{
"data": [
{
"id": 4,
"customer_id": 3,
"service_type_id": 1,
"full_name": "Teja Babu S",
"email": "testemail#gmail.com",
camera_types": 1,
"dvr_types": 1,
"created_at": "2020-01-04 14:18:30",
"updated_at": "2020-01-04 14:18:30",
"camera_type": {
"id": 1,
"name": "Analogue hd",
"description": null,
"status": 1,
"deleted_at": null,
"created_at": "2020-01-04 08:03:45",
"updated_at": "2020-01-04 08:54:23"
},
"dvr_type": {
"id": 1,
"name": "XVR - nvr",
"description": "desc",
"status": 1,
"deleted_at": null,
"created_at": "2020-01-04 08:28:04",
"updated_at": "2020-01-04 08:57:17"
}
}
]
}
I am using the http://www.jsonschema2pojo.org/ for converion. I am not pasting the result to keep the question simple.
package - package
com.tesmachino.saycure.entities.OrderHistory.OrderDetail;
ClassName - OrderDetailsResponse
Target language: Java
Source type: JSON
Annotation style: Moshi
I would like to access the Name from Both camera_type and dvr_type
I am using Moshi + retrofit
OrderDetail
package com.tesmachino.saycure;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.tesmachino.saycure.Auth.TokenManager;
import com.tesmachino.saycure.entities.OrderHistory.OrderDetail.OrderDetailsResponse;
import com.tesmachino.saycure.entities.OrderHistory.OrderHistoryResponse;
import com.tesmachino.saycure.entities.UserDetails.UserDetailsGetResponse;
import com.tesmachino.saycure.network.ApiService;
import com.tesmachino.saycure.network.RetrofitBuilder;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class OrderDetail extends AppCompatActivity {
ApiService service;
TokenManager tokenManager;
Call<OrderDetailsResponse> call;
private static final String TAG = "OrderDetail";
#BindView(R.id.orderdetails_id)
TextView orderId;
#BindView(R.id.orderdetails_client_name)
TextView orderDetailsClientName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_detail);
ButterKnife.bind(this);
tokenManager = TokenManager.getInstance(getSharedPreferences("prefs", MODE_PRIVATE));
service = RetrofitBuilder.createServiceWithAuth(ApiService.class, tokenManager);
}
#Override
protected void onResume() {
//Get the Data from the Intent
if (getIntent().hasExtra("order_id")) {
int order_id = getIntent().getIntExtra("order_id", 1);
Log.d(TAG, "IntentWorking" + order_id);
call = service.orderDetails(order_id);
call.enqueue(new Callback<OrderDetailsResponse>() {
#Override
public void onResponse(Call<OrderDetailsResponse> call, Response<OrderDetailsResponse> response) {
OrderDetailsResponse orderDetails = response.body();
if (orderDetails != null){
}
Log.w(TAG, "onResponse123: " + orderDetails.getData().get(0).getId());
Toast.makeText(OrderDetail.this, "" + response.body().toString(), Toast.LENGTH_SHORT).show();
orderId.setText(String.valueOf(orderDetails.getData().get(0).getId()));
orderDetailsClientName.setText(orderDetails.getData().get(0).getFullName());
Log.w(TAG, "onResponse45321: "+ orderDetails.getData().get(0).getCameraType());
}
#Override
public void onFailure(Call<OrderDetailsResponse> call, Throwable t) {
Log.w(TAG, "onFailure: " + t.getMessage());
Toast.makeText(OrderDetail.this, "Failure" + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(this, "There seems to be an error while fetching the Order Id. Please Try Again", Toast.LENGTH_SHORT).show();
}
super.onResume();
}
}
OrderDetailsResponse
package com.tesmachino.saycure.entities.OrderHistory.OrderDetail;
import com.squareup.moshi.Json;
import org.apache.commons.lang3.builder.ToStringBuilder;
import java.util.List;
public class OrderDetailsResponse {
#Json(name = "data")
private List<OrderDetailsGet> data = null;
public List<OrderDetailsGet> getData() {
return data;
}
public void setData(List<OrderDetailsGet> data) {
this.data = data;
}
#Override
public String toString() {
return new ToStringBuilder(this).append("data", data).toString();
}
}
OrderDetailsGet
package com.tesmachino.saycure.entities.OrderHistory.OrderDetail;
import com.squareup.moshi.Json;
import org.apache.commons.lang3.builder.ToStringBuilder;
public class OrderDetailsGet {
#Json(name = "id")
private Integer id;
#Json(name = "customer_id")
private Integer customerId;
#Json(name = "service_type_id")
private Integer serviceTypeId;
#Json(name = "full_name")
private String fullName;
#Json(name = "email")
private String email;
#Json(name = "address_line_1")
private String addressLine1;
#Json(name = "address_line_2")
private String addressLine2;
#Json(name = "phone_no")
private String phoneNo;
#Json(name = "alternate_phone_no")
private Object alternatePhoneNo;
#Json(name = "land_mark")
private Object landMark;
#Json(name = "area")
private Object area;
#Json(name = "district")
private String district;
#Json(name = "city")
private String city;
#Json(name = "state")
private String state;
#Json(name = "pincode")
private Integer pincode;
#Json(name = "type_of_property")
private Integer typeOfProperty;
#Json(name = "camera_types")
private Integer cameraTypes;
#Json(name = "no_of_cameras")
private Integer noOfCameras;
#Json(name = "dvr_types")
private Integer dvrTypes;
#Json(name = "dvr_channel")
private Integer dvrChannel;
#Json(name = "notes")
private Object notes;
#Json(name = "deleted_at")
private Object deletedAt;
#Json(name = "created_at")
private String createdAt;
#Json(name = "updated_at")
private String updatedAt;
#Json(name = "camera_type")
private CameraType cameraType;
#Json(name = "dvr_type")
private DvrType dvrType;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getCustomerId() {
return customerId;
}
public void setCustomerId(Integer customerId) {
this.customerId = customerId;
}
public Integer getServiceTypeId() {
return serviceTypeId;
}
public void setServiceTypeId(Integer serviceTypeId) {
this.serviceTypeId = serviceTypeId;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddressLine1() {
return addressLine1;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public String getAddressLine2() {
return addressLine2;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
public String getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
public Object getAlternatePhoneNo() {
return alternatePhoneNo;
}
public void setAlternatePhoneNo(Object alternatePhoneNo) {
this.alternatePhoneNo = alternatePhoneNo;
}
public Object getLandMark() {
return landMark;
}
public void setLandMark(Object landMark) {
this.landMark = landMark;
}
public Object getArea() {
return area;
}
public void setArea(Object area) {
this.area = area;
}
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Integer getPincode() {
return pincode;
}
public void setPincode(Integer pincode) {
this.pincode = pincode;
}
public Integer getTypeOfProperty() {
return typeOfProperty;
}
public void setTypeOfProperty(Integer typeOfProperty) {
this.typeOfProperty = typeOfProperty;
}
public Integer getCameraTypes() {
return cameraTypes;
}
public void setCameraTypes(Integer cameraTypes) {
this.cameraTypes = cameraTypes;
}
public Integer getNoOfCameras() {
return noOfCameras;
}
public void setNoOfCameras(Integer noOfCameras) {
this.noOfCameras = noOfCameras;
}
public Integer getDvrTypes() {
return dvrTypes;
}
public void setDvrTypes(Integer dvrTypes) {
this.dvrTypes = dvrTypes;
}
public Integer getDvrChannel() {
return dvrChannel;
}
public void setDvrChannel(Integer dvrChannel) {
this.dvrChannel = dvrChannel;
}
public Object getNotes() {
return notes;
}
public void setNotes(Object notes) {
this.notes = notes;
}
public Object getDeletedAt() {
return deletedAt;
}
public void setDeletedAt(Object deletedAt) {
this.deletedAt = deletedAt;
}
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public String getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(String updatedAt) {
this.updatedAt = updatedAt;
}
public CameraType getCameraType() {
return cameraType;
}
public void setCameraType(CameraType cameraType) {
this.cameraType = cameraType;
}
public DvrType getDvrType() {
return dvrType;
}
public void setDvrType(DvrType dvrType) {
this.dvrType = dvrType;
}
#Override
public String toString() {
return new ToStringBuilder(this).append("id", id).append("customerId", customerId).append("serviceTypeId", serviceTypeId).append("fullName", fullName).append("email", email).append("addressLine1", addressLine1).append("addressLine2", addressLine2).append("phoneNo", phoneNo).append("alternatePhoneNo", alternatePhoneNo).append("landMark", landMark).append("area", area).append("district", district).append("city", city).append("state", state).append("pincode", pincode).append("typeOfProperty", typeOfProperty).append("cameraTypes", cameraTypes).append("noOfCameras", noOfCameras).append("dvrTypes", dvrTypes).append("dvrChannel", dvrChannel).append("notes", notes).append("deletedAt", deletedAt).append("createdAt", createdAt).append("updatedAt", updatedAt).append("cameraType", cameraType).append("dvrType", dvrType).toString();
}
}
If you are just trying to the the name from camera_type and dvr_type, you can do:
//This assumes that you have a getCameraType & getDvrTypes method in your OrderDetailsGet class
String camera_name = orderDetails.getData().get(0).getCameraType().getName()
String dvr_name = orderDetails.getData().get(0).getDvrTypes().getName()

How to convert this nested json string to a java object?

I have the following JSON string in a "special" format.
I want to convert it to an object in java but I don't know how to access single values for example the value of location or "resolved_at".
I tried with GSON and JSONPOBJECT but it doesn't work with this one.
{
"result": {
"upon_approval": "proceed",
"location": {
"link": "https://instance.service- now.com/api/now/table/cmn_location/108752c8c611227501d4ab0e392ba97f",
"value": "108752c8c611227501d4ab0e392ba97f"
},
"expected_start": "",
"reopen_count": "",
"sys_domain": {
"link": "https://instance.service- now.com/api/now/table/sys_user_group/global",
"value": "global"
},
"description": "",
"activity_due": "2016-01-22 16:12:37",
"sys_created_by": "glide.maint",
"resolved_at": "",
"assigned_to": {
"link": "https://instance.service- now.com/api/now/table/sys_user/681b365ec0a80164000fb0b05854a0cd",
"value": "681b365ec0a80164000fb0b05854a0cd"
},
"business_stc": "",
"wf_activity": "",
"sys_domain_path": "/",
"cmdb_ci": {
"link": "https://instance.service- now.com/api/now/table/cmdb_ci/281190e3c0a8000b003f593aa3f20ca6",
"value": "281190e3c0a8000b003f593aa3f20ca6"
},
"opened_by": {
"link": "https://instance.service- now.com/api/now/table/sys_user/glide.maint",
"value": "glide.maint"
},
"subcategory": "",
"comments": ""
}
}
Just create an object and use the objectmapper like:
Myclass myclass = objectMapper.readValue(json, Myclass.class);
But according to https://jsoneditoronline.org/ your json is not valid.
Used an online converter to create the classes, after removing the errors:
-----------------------------------com.example.AssignedTo.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class AssignedTo {
#SerializedName("link")
#Expose
private String link;
#SerializedName("value")
#Expose
private String value;
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
-----------------------------------com.example.CmdbCi.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class CmdbCi {
#SerializedName("link")
#Expose
private String link;
#SerializedName("value")
#Expose
private String value;
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
-----------------------------------com.example.Example.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("result")
#Expose
private Result result;
public Result getResult() {
return result;
}
public void setResult(Result result) {
this.result = result;
}
}
-----------------------------------com.example.Location.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Location {
#SerializedName("link")
#Expose
private String link;
#SerializedName("value")
#Expose
private String value;
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
-----------------------------------com.example.OpenedBy.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class OpenedBy {
#SerializedName("link")
#Expose
private String link;
#SerializedName("value")
#Expose
private String value;
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
-----------------------------------com.example.Result.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Result {
#SerializedName("upon_approval")
#Expose
private String uponApproval;
#SerializedName("location")
#Expose
private Location location;
#SerializedName("expected_start")
#Expose
private String expectedStart;
#SerializedName("reopen_count")
#Expose
private String reopenCount;
#SerializedName("sys_domain")
#Expose
private SysDomain sysDomain;
#SerializedName("description")
#Expose
private String description;
#SerializedName("activity_due")
#Expose
private String activityDue;
#SerializedName("sys_created_by")
#Expose
private String sysCreatedBy;
#SerializedName("resolved_at")
#Expose
private String resolvedAt;
#SerializedName("assigned_to")
#Expose
private AssignedTo assignedTo;
#SerializedName("business_stc")
#Expose
private String businessStc;
#SerializedName("wf_activity")
#Expose
private String wfActivity;
#SerializedName("sys_domain_path")
#Expose
private String sysDomainPath;
#SerializedName("cmdb_ci")
#Expose
private CmdbCi cmdbCi;
#SerializedName("opened_by")
#Expose
private OpenedBy openedBy;
#SerializedName("subcategory")
#Expose
private String subcategory;
#SerializedName("comments")
#Expose
private String comments;
public String getUponApproval() {
return uponApproval;
}
public void setUponApproval(String uponApproval) {
this.uponApproval = uponApproval;
}
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
this.location = location;
}
public String getExpectedStart() {
return expectedStart;
}
public void setExpectedStart(String expectedStart) {
this.expectedStart = expectedStart;
}
public String getReopenCount() {
return reopenCount;
}
public void setReopenCount(String reopenCount) {
this.reopenCount = reopenCount;
}
public SysDomain getSysDomain() {
return sysDomain;
}
public void setSysDomain(SysDomain sysDomain) {
this.sysDomain = sysDomain;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getActivityDue() {
return activityDue;
}
public void setActivityDue(String activityDue) {
this.activityDue = activityDue;
}
public String getSysCreatedBy() {
return sysCreatedBy;
}
public void setSysCreatedBy(String sysCreatedBy) {
this.sysCreatedBy = sysCreatedBy;
}
public String getResolvedAt() {
return resolvedAt;
}
public void setResolvedAt(String resolvedAt) {
this.resolvedAt = resolvedAt;
}
public AssignedTo getAssignedTo() {
return assignedTo;
}
public void setAssignedTo(AssignedTo assignedTo) {
this.assignedTo = assignedTo;
}
public String getBusinessStc() {
return businessStc;
}
public void setBusinessStc(String businessStc) {
this.businessStc = businessStc;
}
public String getWfActivity() {
return wfActivity;
}
public void setWfActivity(String wfActivity) {
this.wfActivity = wfActivity;
}
public String getSysDomainPath() {
return sysDomainPath;
}
public void setSysDomainPath(String sysDomainPath) {
this.sysDomainPath = sysDomainPath;
}
public CmdbCi getCmdbCi() {
return cmdbCi;
}
public void setCmdbCi(CmdbCi cmdbCi) {
this.cmdbCi = cmdbCi;
}
public OpenedBy getOpenedBy() {
return openedBy;
}
public void setOpenedBy(OpenedBy openedBy) {
this.openedBy = openedBy;
}
public String getSubcategory() {
return subcategory;
}
public void setSubcategory(String subcategory) {
this.subcategory = subcategory;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
}
-----------------------------------com.example.SysDomain.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class SysDomain {
#SerializedName("link")
#Expose
private String link;
#SerializedName("value")
#Expose
private String value;
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
Edit: As i see, the code above will not work OOTB. I've got it working doeing the following steps:
Replace #SerializedName with #JsonProperty
then:
ObjectMapper mapper = new ObjectMapper();
Example example = mapper.readValue(json, Example.class);

convert xml to Java object using jackson

I want to convert XML to JSON using Jackson library. I have tried below code to get Json as below using jackson but I can't. if I tried using json, I can but I want to know how to do with Jackson library.
#RequestMapping(value="/convertXMLtoJson",method=RequestMethod.POST,consumes = MediaType.APPLICATION_XML_VALUE)
public Map<String,Object> convertXMLtoJson(#RequestBody String strXMLData) {
Map<String,Object> objresponseMessage = null;
ObjectMapper objObjectMapper = new ObjectMapper();
Employee objEmployee = null;
try {
JSONObject obj = XML.toJSONObject(strXMLData);
ObjectMapper objectMapper = new XmlMapper();
objEmployee = objectMapper.readValue(strXMLData, Employee.class);
objEmployeeService.save(objEmployee);
} catch (Exception e) {
e.printStackTrace();
}
return objresponseMessage;
}
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of java.util.HashSet out of VALUE_STRING token
at [Source: (StringReader); line: 5, column: 15] (through reference chain: com.example.springboot.bean.Employee["Skills"])
<EmployeeDetail>
<FirstName>A</FirstName>
<LastName>Z</LastName>
<Age>20</Age>
<Skills>Java</Skills>
<Skills>J2EE</Skills>
<Skills>MSSQl</Skills>
<Skills>JAVA</Skills>
<TotalExperience>4</TotalExperience>
<JobDetails>
<CompanyName>1</CompanyName>
<Experience>1.5</Experience>
<Technologies>Java</Technologies>
<Technologies>WebServices</Technologies>
<Technologies>MSSQL</Technologies>
<Technologies>J2EE</Technologies>
<Location>India</Location>
</JobDetails>
<JobDetails>
<CompanyName>2</CompanyName>
<Experience>2.5</Experience>
<Technologies>Java</Technologies>
<Technologies>J2EE</Technologies>
<Technologies>MySQL</Technologies>
<Technologies>Spring</Technologies>
<Location>India</Location>
</JobDetails>
</EmployeeDetail>
Expected Json as(Output Excepted)
{
"EmployeeDetail": {
"FirstName": "A",
"LastName": "Z",
"Age": "20",
"Skills": [
"Java",
"J2EE",
"MSSQl",
"JAVA"
],
"TotalExperience": "4",
"JobDetails": [
{
"CompanyName": "1",
"Experience": "1.5",
"Technologies": [
"Java",
"WebServices",
"MSSQL",
"J2EE"
],
"Location": "India"
},
{
"CompanyName": "2",
"Experience": "2.5",
"Technologies": [
"Java",
"J2EE",
"MySQL",
"Spring"
],
"Location": "India"
}
]
}
}
Can Anyone help me to understand using Jackson library
import java.io.Serializable;
import java.util.List;
import java.util.Set;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
#Document
#JacksonXmlRootElement(localName="EmployeeDetail")
public class Employee implements Serializable {
#Id
private String userId;
#JacksonXmlProperty(localName="FirstName")
#JsonProperty("FirstName")
private String firstName;
#JacksonXmlProperty(localName="LastName")
#JsonProperty("LastName")
private String lastName;
#JacksonXmlProperty(localName="Age")
#JsonProperty("Age")
private Integer age;
#JacksonXmlElementWrapper(localName="Skills")
#JsonProperty("Skills")
private Set<String> skills;
#JacksonXmlProperty(localName="JobDetails")
#JsonProperty("JobDetails")
private List<JobDetails> jobDetails;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public List<JobDetails> getJobDetails() {
return jobDetails;
}
public void setJobDetails(List<JobDetails> jobDetails) {
this.jobDetails = jobDetails;
}
public Set<String> getSkills() {
return skills;
}
public void setSkills(Set<String> skills) {
this.skills = skills;
}
}
import java.util.Set;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
#JacksonXmlRootElement(localName="JobDetails")
public class JobDetails {
JobDetails(String str) {
}
#JacksonXmlProperty(localName="CompanyName")
#JsonProperty("CompanyName")
private String companyName;
#JacksonXmlProperty(localName="Experience")
#JsonProperty("Experience")
private Integer experience;
#JacksonXmlProperty(localName="Location")
#JsonProperty("Location")
private String location;
#JacksonXmlElementWrapper(localName="Technologies")
#JsonProperty("Technologies")
private Set<String> technologies;
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public Integer getExperience() {
return experience;
}
public void setExperience(Integer experience) {
this.experience = experience;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public Set<String> getTechnologies() {
return technologies;
}
public void setTechnologies(Set<String> technologies) {
this.technologies = technologies;
}
}
Change your xml input data , whatever inputs are as a collection group them in tag.and modify localName in annotation " #JacksonXmlElementWrapper" in java file. Here is what is did.
<EmployeeDetail>
<FirstName>A</FirstName>
<LastName>Z</LastName>
<Age>20</Age>
<skillset>
<Skills>Java</Skills>
<Skills>J2EE</Skills>
<Skills>MSSQl</Skills>
<Skills>JAVA</Skills>
</skillset>
<TotalExperience>4</TotalExperience>
<jobs>
<JobDetails>
<CompanyName>1</CompanyName>
<Experience>1.5</Experience>
<technologyList>
<Technologies>Java</Technologies>
<Technologies>WebServices</Technologies>
<Technologies>MSSQL</Technologies>
<Technologies>J2EE</Technologies>
</technologyList>
<Location>India</Location>
</JobDetails>
<JobDetails>
<CompanyName>2</CompanyName>
<Experience>2.5</Experience>
<technologyList>
<Technologies>Java</Technologies>
<Technologies>J2EE</Technologies>
<Technologies>MySQL</Technologies>
<Technologies>Spring</Technologies>
</technologyList>
<Location>India</Location>
</JobDetails>
</jobs>
</EmployeeDetail>
Now modify your Employee.java class to following
import java.util.List;
import java.util.Set;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
#Document
#JacksonXmlRootElement(localName="EmployeeDetail")
public class Employee implements Serializable {
#Id
private String userId;
#JacksonXmlProperty(localName="FirstName")
#JsonProperty("FirstName")
private String firstName;
#JacksonXmlProperty(localName="LastName")
#JsonProperty("LastName")
private String lastName;
#JacksonXmlProperty(localName="Age")
#JsonProperty("Age")
private Integer age;
#JacksonXmlElementWrapper(localName="skillset")
#JsonProperty("Skills")
private Set<String> skills;
#JacksonXmlElementWrapper(localName="jobs")
#JsonProperty("JobDetails")
private List<JobDetails> jobDetails;
#JacksonXmlProperty(localName="TotalExperience")
#JsonProperty("totalExperience")
private Integer totalExperience;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public List<JobDetails> getJobDetails() {
return jobDetails;
}
public void setJobDetails(List<JobDetails> jobDetails) {
this.jobDetails = jobDetails;
}
public Set<String> getSkills() {
return skills;
}
public void setSkills(Set<String> skills) {
this.skills = skills;
}
public Integer getTotalExperience() {
return totalExperience;
}
public void setTotalExperience(Integer totalExperience) {
this.totalExperience = totalExperience;
}
}
your Jobdetail.java to
import java.util.Set;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
#JacksonXmlRootElement(localName="JobDetails")
public class JobDetails {
public JobDetails() {
// TODO Auto-generated constructor stub
}
JobDetails(String str) {
}
#JacksonXmlProperty(localName="CompanyName")
#JsonProperty("CompanyName")
private String companyName;
#JacksonXmlProperty(localName="Experience")
#JsonProperty("Experience")
private Float experience;
#JacksonXmlProperty(localName="Location")
#JsonProperty("Location")
private String location;
#JacksonXmlElementWrapper(localName="technologyList")
#JsonProperty("Technologies")
private Set<String> technologies;
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public FloatgetExperience() {
return experience;
}
public void setExperience(Floatexperience) {
this.experience = experience;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public Set<String> getTechnologies() {
return technologies;
}
public void setTechnologies(Set<String> technologies) {
this.technologies = technologies;
}
}
And use below method to convert your xml to Json;
public static String convertXMLtoJson( String inputxml) {
String json="";
try {
ObjectMapper objectMapper = new XmlMapper();
ObjectMapper jsonMapper = new ObjectMapper();
Employee emp = objectMapper.readValue(inputxml, Employee.class);
json =jsonMapper.writeValueAsString(emp);
System.out.println(jsonMapper.writeValueAsString(emp));
} catch (Exception e) {
e.printStackTrace();
}
return json;
}
Here's what json data i'm getting
{"userId":null,"FirstName":"A","LastName":"Z","Age":20,"Skills":["JAVA","Java","J2EE","MSSQl"],"JobDetails":[{"CompanyName":"1","Experience":1.5,"Location":"India","Technologies":["Java","WebServices","J2EE","MSSQL"]},{"CompanyName":"2","Experience":2.5,"Location":"India","Technologies":["Java","MySQL","J2EE","Spring"]}],"totalExperience":4}
Could be useful know the implementation of Employee class.
Are you skills field annotated with #JsonProperty("Skills") as capitalized?
#JsonProperty("Skills")
private Set<String> skills;
Case sensitive should be matter.

Categories

Resources