I created one Object class which will be my root element and in that I have two attributes and one element shown below:
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Object {
private String id;
private String type;
List <UniqueId> UniqueId;
public List<UniqueId> getUniqueId() {
return UniqueId;
}
public void setUniqueId(List<UniqueId> uniqueId) {
UniqueId = uniqueId;
}
#XmlAttribute
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#XmlAttribute
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Object() {
super();
}
public Object(String id, String type, List<classes.UniqueId> uniqueId) {
super();
this.id = id;
this.type = type;
UniqueId = uniqueId;
}
}
and then one class for List <UniqueId> UniqueId;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class UniqueId {
private String Uid;
public String getUid() {
return Uid;
}
public void setUid(String uid) {
Uid = uid;
}
public UniqueId(String uid) {
super();
Uid = uid;
}
public UniqueId() {
super();
}
}
and in the main class, I want to Unmarshal the UniqueId data from VPMobject and I'm getting null value there. How can I fetch the uniqueId if there are n UId's present in the xml file?
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import pojoClasses.VPMObject;
public class MarshalEAD {
public static void main(String[] args) {
try {
File f1 = new File("src\\xmlData\\Test1.xml");
JAXBContext contextObj = JAXBContext.newInstance(Assembly.class);
Unmarshaller unmarshal = contextObj.createUnmarshaller();
// add information or objects to be fetched and written as output
Assembly AD= (Assembly)unmarshal.unmarshal(f1);
System.out.println("Extracted Xml File Information:\n\t");
System.out.println("Root Element: ");
List<VPMObject> list = AD.getVPMObject();
for(VPMObject fetch:list) {
System.out.println("ID: " + fetch.getId());
System.out.println("Type: " + fetch.getType());
System.out.println("UniqueId: " + fetch.getUniqueId() );
}
}
catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
}
}
}
Related
I have this JAXB component which I would like to get as a list:
#XmlRootElement(name = "payment")
#XmlAccessorType(XmlAccessType.FIELD)
public class Transaction {
#XmlElement(name = "transaction_types")
public TransactionTypes transactionTypes;
}
public class TransactionTypes {
#XmlElement(name = "transaction_type")
public String transaction_type;
#XmlAttribute
public String name;
public String getTransaction_type() {
return transaction_type;
}
public void setTransaction_type(String transaction_type) {
this.transaction_type = transaction_type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
XML structure:
<payment>
<transaction_types>
<transaction_type name="type1"/>
<transaction_type name="type2"/>
<transaction_type name="type3"/>
</transaction_types>
</payment>
The question is how I can get all transaction types as a list?
Can you give me some idea how should I modify the JAXB Object?
EDIT:
I tried this
#XmlRootElement(name = "payment")
#XmlAccessorType(XmlAccessType.FIELD)
public class Transaction {
#XmlElementWrapper(name = "transaction_types")
public List<TransactionTypes> transactionTypes;
}
Inner object which will hold the list:
public class TransactionTypes {
#XmlElement(name = "transaction_type")
public String transaction_type;
#XmlAttribute
public String name;
public String getTransaction_type() {
return transaction_type;
}
public void setTransaction_type(String transaction_type) {
this.transaction_type = transaction_type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
To get all the transaction_type as a list, I have somewhat modified your code. I have introduced a new class TransactionList which will contain the list of transaction_type
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 = "payment")
#XmlAccessorType(XmlAccessType.FIELD)
public class Transaction {
#XmlElement(name = "transaction_types")
public TransactionList transactionList;
public Transaction() {
super();
}
#Override
public String toString() {
return "Transaction [TransactionList=" + transactionList + "]";
}
}
TransactionList class
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
#XmlAccessorType(XmlAccessType.FIELD)
public class TransactionList {
#XmlElement(name = "transaction_type")
public List<TransactionType> transactionType;
public TransactionList(List<TransactionType> transactionTypes) {
transactionType = transactionTypes;
}
public TransactionList() {
super();
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (TransactionType transactionType : transactionType) {
sb.append(transactionType + "\n");
}
return sb.toString();
}
}
TransactionType class
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
#XmlAccessorType(XmlAccessType.FIELD)
public class TransactionType {
#XmlElement(name = "transaction_type")
private String transaction_type;
#XmlAttribute
private String name;
public TransactionType(String transaction_type, String name) {
this.transaction_type = transaction_type;
this.name = name;
}
public TransactionType() {
}
public String getTransaction_type() {
return transaction_type;
}
public void setTransaction_type(String transaction_type) {
this.transaction_type = transaction_type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return "TransactionTypes [transaction_type=" + transaction_type + ", name=" + name + "]";
}
}
main method
public static void main(String[] args) throws Exception {
JAXBContext context = JAXBContext.newInstance(Transaction.class);
Unmarshaller um = context.createUnmarshaller();
Transaction transaction = (Transaction) um.unmarshal(new FileReader(FILE));
System.out.println(transaction);
}
You can also check the output by directly changing the variable transactionType to List in Transaction table and assigning XMLElementWrapper annotation to it
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "payment")
#XmlAccessorType(XmlAccessType.FIELD)
public class Transaction {
#XmlElementWrapper(name = "transaction_types")
public List<TransactionType> transactionType;
public Transaction() {
}
}
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Version;
import org.hibernate.annotations.GenericGenerator;
import com.lue.billingsystem.enums.Status;
import com.lue.billingsystem.enums.Types;
#Entity
#Table(name="product_tab")
public class Product implements Serializable{
private static final long serialVersionUID = 8919320309645697466L;
#Id
#Column(name="prod_id",updatable=false)
#GenericGenerator(name="product_tab_genetator",strategy="increment")
#GeneratedValue(generator="product_tab_genetator")
private Long id;
private String name;
#Enumerated(EnumType.STRING)
#Column(name = "type")
private Types type;
#Column(name = "status")
#Enumerated(EnumType.STRING)
private Status status;
#Column(name = "description", length = 200)
private String description;
#OneToMany(mappedBy="product")
private List<Charge> charges;
#Column(name = "create_date", columnDefinition = "DATETIME")
private Date createDate;
#Column(name = "update_date", columnDefinition = "DATETIME")
private Date updateDate;
//#Version
private Integer version;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Types getType() {
return type;
}
public void setType(Types type) {
this.type = type;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<Charge> getCharges() {
return charges;
}
public void setCharges(List<Charge> charges) {
this.charges = charges;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public Date getUpdateDate() {
return updateDate;
}
public void setUpdateDate(Date updateDate) {
this.updateDate = updateDate;
}
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
}
import org.springframework.http.HttpStatus;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.lue.billingsystem.enums.utils.StatusDeserializer;
import com.lue.billingsystem.exception.BillingException;
#JsonDeserialize(using = StatusDeserializer.class)
public enum Status {
ACTIVE("Active"), INACTIVE("Inactive");
private final String text;
Status(final String text) {
this.text = text;
}
#Override
public String toString() {
return text;
}
public String getText() {
return this.text;
}
public static Status fromText(String text) {
for (Status r : Status.values()) {
if (r.getText().equals(text)) {
System.out.println(r);
return r;
}
}
throw new BillingException("Your Status not valied: "+text +" ", HttpStatus.BAD_REQUEST, 400);
}
}
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.lue.billingsystem.enums.Status;
public class StatusDeserializer extends JsonDeserializer<Status> {
#Override
public Status deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
throws IOException, JsonProcessingException {
ObjectCodec oc = jsonParser.getCodec();
JsonNode node = oc.readTree(jsonParser);
if (node == null) {
return null;
}
String text = node.textValue(); // gives "A" from the request
if (text == null) {
return null;
}
//System.out.println(Status.fromText(text) + "---------------");
return Status.fromText(text);
}
}
How to enum mapping with jpa Spring boot why not save enum value in DB in DB saving enum key when i saving product in databse not save status like Active it always save ACTIVE
You just need to pay attention to the enum values when the table is being created.
What are the enum values in the table e.g. in status column, are the values defined as 'Active', 'Inactive' or 'ACTIVE', 'INACTIVE'. That's what will determine the value saved.
If the enum values are defined as 'ACTIVE', 'INACTIVE', if you insert 'active' as the value for status, it will change to 'ACTIVE' inside the database because it inserts based on the pre defined enum values.
I've a very big XML string. Im posting here only part of the XML object. I'm trying to convert this XML to Java object. My first question is, should I need to create Java object of total XML tag values or can I have create the Java object of only selected inner XML objects? Please find my XML string.
<DATAPACKET REQUEST-ID = "2">
<HEADER>
<RESPONSE-TYPE CODE="1" DESCRIPTION="Response DataPacket"/>
<SEARCH-RESULT-LIST>
<SEARCH-RESULT-ITEM>
<NAME MATCHED="TRUE"/>
</SEARCH-RESULT-ITEM>
</SEARCH-RESULT-LIST>
</HEADER>
<BODY>
<CONS_SCORE>
<SCORE>0</SCORE>
<REASON1>
<HEADER></HEADER>
<DESCRIPTION></DESCRIPTION>
</REASON1>
<REASON2>
<HEADER></HEADER>
<DESCRIPTION></DESCRIPTION>
</REASON2>
<REASON3>
<HEADER></HEADER>
<DESCRIPTION></DESCRIPTION>
</REASON3>
<REASON4>
<HEADER></HEADER>
<DESCRIPTION></DESCRIPTION>
</REASON4>
</CONS_SCORE>
<CONSUMER_PROFILE2>
<CONSUMER_DETAILS2>
<RUID>1234</RUID>
<NAME>ABC</NAME>
<DATE_OF_BIRTH>1980-03-03T00:00:00+03:00</DATE_OF_BIRTH>
<GENDER>001</GENDER>
</CONSUMER_DETAILS2>
<ID_DETAILS2>
<SLNO>1</SLNO>
<SOURCE_ID>001</SOURCE_ID>
<ID_VALUE>2806</ID_VALUE>
<EXP_DATE>2018-07-13T00:00:00+03:00</EXP_DATE>
</ID_DETAILS2>
</CONSUMER_PROFILE2>
</BODY>
</DATAPACKET>
In the above object, I want to fetch only CONSUMER_PROFILE2 object. Here is my Dto class
#XmlRootElement(name = "DATAPACKET")
public class ConsumerProfileDto {
private ConsumerDetailsDto CONSUMER_DETAILS2;
private IdDetailsDto ID_DETAILS2;
public ConsumerDetailsDto getCONSUMER_DETAILS2() {
return CONSUMER_DETAILS2;
}
public void setCONSUMER_DETAILS2(ConsumerDetailsDto cONSUMER_DETAILS2) {
CONSUMER_DETAILS2 = cONSUMER_DETAILS2;
}
public IdDetailsDto getID_DETAILS2() {
return ID_DETAILS2;
}
public void setID_DETAILS2(IdDetailsDto iD_DETAILS2) {
ID_DETAILS2 = iD_DETAILS2;
}
}
CONSUMER_DETAILS2 class
#XmlRootElement(name = "CONSUMER_DETAILS2")
public class ConsumerDetailsDto {
private String NAME;
private String DATE_OF_BIRTH;
private String GENDER;
private String NATIONALITY;
public String getNAME() {
return NAME;
}
public void setNAME(String nAME) {
NAME = nAME;
}
public String getDATE_OF_BIRTH() {
return DATE_OF_BIRTH;
}
public void setDATE_OF_BIRTH(String dATE_OF_BIRTH) {
DATE_OF_BIRTH = dATE_OF_BIRTH;
}
public String getGENDER() {
return GENDER;
}
public void setGENDER(String gENDER) {
GENDER = gENDER;
}
public String getNATIONALITY() {
return NATIONALITY;
}
public void setNATIONALITY(String nATIONALITY) {
NATIONALITY = nATIONALITY;
}
Here is the code of unmarshalling
JAXBContext jaxbContext = JAXBContext.newInstance(ConsumerProfileDto.class);
StringReader reader = new StringReader(responseXML);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
ConsumerDetailsDto que= (ConsumerDetailsDto) jaxbUnmarshaller.unmarshal(reader);
System.out.println(que.getDATE_OF_BIRTH());
System.out.println(que.getGENDER());;
System.out.println(que.getNAME());
P.S
I've used DocumentBuilder and I'm able to fetch the values using it. But, I want to extract using Jaxb.
You can't annotate as #XmlRootElement the Java class mirroring the XML element that you're interested on. You have to mirror in Java all the XML elements from the topmost element in the XML file (DATAPACKET) to the lowest ones (CONSUMER_DETAILS2 and ID_DETAILS2) in the path that you're interested, even if you're only interested in some of them.
I assume that the operator isn't interested in RUID (because the class CONSUMER_DETAILS2 doesn't include a field for this XML element), and also that the field NATIONALITY is not going to be loaded from this XML.
If the input XML of the question were in a file named input2.xml, then I'd have the following Java classes:
DataPacket
package test;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlAccessorType(XmlAccessType.NONE)
#XmlRootElement(name = "DATAPACKET")
public class DataPacket {
#XmlAttribute(name = "REQUEST_ID")
private int REQUEST_ID;
#XmlElement(name ="BODY")
private Body BODY;
public DataPacket(){}
public int getREQUEST_ID() {
return REQUEST_ID;
}
public void setREQUEST_ID(int REQUEST_ID) {
this.REQUEST_ID = REQUEST_ID;
}
public Body getBODY() {
return BODY;
}
public void setBODY(Body BODY) {
this.BODY = BODY;
}
}
Body
package test;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
#XmlAccessorType(XmlAccessType.NONE)
class Body {
#XmlElement(name = "CONSUMER_PROFILE2")
private ConsumerProfile profile;
public Body(){}
public ConsumerProfile getProfile() {
return profile;
}
public void setProfile(ConsumerProfile profile) {
this.profile = profile;
}
}
ConsumerProfile
package test;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
#XmlAccessorType(XmlAccessType.NONE)
public class ConsumerProfile {
#XmlElement(name = "CONSUMER_DETAILS2")
private ConsumerDetails CONSUMER_DETAILS2;
#XmlElement(name = "ID_DETAILS2")
private IdDetails ID_DETAILS2;
public ConsumerProfile(){}
public ConsumerDetails getCONSUMER_DETAILS2() {
return CONSUMER_DETAILS2;
}
public void setCONSUMER_DETAILS2(ConsumerDetails cONSUMER_DETAILS2) {
CONSUMER_DETAILS2 = cONSUMER_DETAILS2;
}
public IdDetails getID_DETAILS2() {
return ID_DETAILS2;
}
public void setID_DETAILS2(IdDetails iD_DETAILS2) {
ID_DETAILS2 = iD_DETAILS2;
}
}
ConsumerDetails
package test;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
#XmlAccessorType(XmlAccessType.NONE)
class ConsumerDetails {
#XmlElement(name="NAME")
private String NAME;
#XmlElement(name="DATE_OF_BIRTH")
private String DATE_OF_BIRTH;
#XmlElement(name="GENDER")
private String GENDER;
private String NATIONALITY;
public ConsumerDetails(){}
public String getNAME() {
return NAME;
}
public void setNAME(String nAME) {
NAME = nAME;
}
public String getDATE_OF_BIRTH() {
return DATE_OF_BIRTH;
}
public void setDATE_OF_BIRTH(String dATE_OF_BIRTH) {
DATE_OF_BIRTH = dATE_OF_BIRTH;
}
public String getGENDER() {
return GENDER;
}
public void setGENDER(String gENDER) {
GENDER = gENDER;
}
public String getNATIONALITY() {
return NATIONALITY;
}
public void setNATIONALITY(String nATIONALITY) {
NATIONALITY = nATIONALITY;
}
}
IdDetails
package test;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
#XmlAccessorType(XmlAccessType.NONE)
class IdDetails {
#XmlElement(name="SLNO")
private int SLNO;
#XmlElement(name="SOURCE_ID")
private String SOURCE_ID;
#XmlElement(name="ID_VALUE")
private int ID_VALUE;
#XmlElement(name="EXP_DATE")
private String EXP_DATE;
public IdDetails(){}
public int getSLNO() {
return SLNO;
}
public void setSLNO(int SLNO) {
this.SLNO = SLNO;
}
public String getSOURCE_ID() {
return SOURCE_ID;
}
public void setSOURCE_ID(String SOURCE_ID) {
this.SOURCE_ID = SOURCE_ID;
}
public int getID_VALUE() {
return ID_VALUE;
}
public void setID_VALUE(int ID_VALUE) {
this.ID_VALUE = ID_VALUE;
}
public String getEXP_DATE() {
return EXP_DATE;
}
public void setEXP_DATE(String EXP_DATE) {
this.EXP_DATE = EXP_DATE;
}
}
Also, inside the same "test" package the jaxb.index file with:
DataPacket
ConsumerProfile
ConsumerDetails
IdDetails
Then, when testing with this Test class:
package test;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
public class Test {
public static void main(String[] args) {
try{
JAXBContext jc = JAXBContext.newInstance(DataPacket.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("input2.xml");
DataPacket dp = (DataPacket) unmarshaller.unmarshal(xml);
Body body = dp.getBODY();
ConsumerProfile profile = body.getProfile();
ConsumerDetails consumerDetail = profile.getCONSUMER_DETAILS2();
IdDetails idDetails = profile.getID_DETAILS2();
System.out.println("ConsumerDetails name:"+consumerDetail.getNAME()+
" date of birth:"+consumerDetail.getDATE_OF_BIRTH()+
" gender:"+consumerDetail.getGENDER()+
"IdDetails SLNO:"+idDetails.getSLNO()+
" SOURCE_ID:"+idDetails.getSOURCE_ID()+
" ID_VALUE:"+idDetails.getID_VALUE()+
" EXP_DATE:"+idDetails.getEXP_DATE());
}
catch(JAXBException e){
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
I've a very big XML string. Im posting here only part of the XML object. I'm trying to convert this XML to Java object. My first question is, should I need to create Java object of total XML tag values or can I have create the Java object of only selected inner XML objects? Please find my XML string.
<DATAPACKET REQUEST-ID = "2">
<HEADER>
<RESPONSE-TYPE CODE="1" DESCRIPTION="Response DataPacket"/>
<SEARCH-RESULT-LIST>
<SEARCH-RESULT-ITEM>
<NAME MATCHED="TRUE"/>
</SEARCH-RESULT-ITEM>
</SEARCH-RESULT-LIST>
</HEADER>
<BODY>
<CONS_SCORE>
<SCORE>0</SCORE>
<REASON1>
<HEADER></HEADER>
<DESCRIPTION></DESCRIPTION>
</REASON1>
<REASON2>
<HEADER></HEADER>
<DESCRIPTION></DESCRIPTION>
</REASON2>
<REASON3>
<HEADER></HEADER>
<DESCRIPTION></DESCRIPTION>
</REASON3>
<REASON4>
<HEADER></HEADER>
<DESCRIPTION></DESCRIPTION>
</REASON4>
</CONS_SCORE>
<CONSUMER_PROFILE2>
<CONSUMER_DETAILS2>
<RUID>1234</RUID>
<NAME>ABC</NAME>
<DATE_OF_BIRTH>1980-03-03T00:00:00+03:00</DATE_OF_BIRTH>
<GENDER>001</GENDER>
</CONSUMER_DETAILS2>
<ID_DETAILS2>
<SLNO>1</SLNO>
<SOURCE_ID>001</SOURCE_ID>
<ID_VALUE>2806</ID_VALUE>
<EXP_DATE>2018-07-13T00:00:00+03:00</EXP_DATE>
</ID_DETAILS2>
</CONSUMER_PROFILE2>
</BODY>
</DATAPACKET>
In the above object, I want to fetch only CONSUMER_PROFILE2 object. Here is my Dto class
#XmlRootElement(name = "DATAPACKET")
public class ConsumerProfileDto {
private ConsumerDetailsDto CONSUMER_DETAILS2;
private IdDetailsDto ID_DETAILS2;
public ConsumerDetailsDto getCONSUMER_DETAILS2() {
return CONSUMER_DETAILS2;
}
public void setCONSUMER_DETAILS2(ConsumerDetailsDto cONSUMER_DETAILS2) {
CONSUMER_DETAILS2 = cONSUMER_DETAILS2;
}
public IdDetailsDto getID_DETAILS2() {
return ID_DETAILS2;
}
public void setID_DETAILS2(IdDetailsDto iD_DETAILS2) {
ID_DETAILS2 = iD_DETAILS2;
}
}
CONSUMER_DETAILS2 class
#XmlRootElement(name = "CONSUMER_DETAILS2")
public class ConsumerDetailsDto {
private String NAME;
private String DATE_OF_BIRTH;
private String GENDER;
private String NATIONALITY;
public String getNAME() {
return NAME;
}
public void setNAME(String nAME) {
NAME = nAME;
}
public String getDATE_OF_BIRTH() {
return DATE_OF_BIRTH;
}
public void setDATE_OF_BIRTH(String dATE_OF_BIRTH) {
DATE_OF_BIRTH = dATE_OF_BIRTH;
}
public String getGENDER() {
return GENDER;
}
public void setGENDER(String gENDER) {
GENDER = gENDER;
}
public String getNATIONALITY() {
return NATIONALITY;
}
public void setNATIONALITY(String nATIONALITY) {
NATIONALITY = nATIONALITY;
}
Here is the code of unmarshalling
JAXBContext jaxbContext = JAXBContext.newInstance(ConsumerProfileDto.class);
StringReader reader = new StringReader(responseXML);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
ConsumerDetailsDto que= (ConsumerDetailsDto) jaxbUnmarshaller.unmarshal(reader);
System.out.println(que.getDATE_OF_BIRTH());
System.out.println(que.getGENDER());;
System.out.println(que.getNAME());
P.S
I've used DocumentBuilder and I'm able to fetch the values using it. But, I want to extract using Jaxb.
You can't annotate as #XmlRootElement the Java class mirroring the XML element that you're interested on. You have to mirror in Java all the XML elements from the topmost element in the XML file (DATAPACKET) to the lowest ones (CONSUMER_DETAILS2 and ID_DETAILS2) in the path that you're interested, even if you're only interested in some of them.
I assume that the operator isn't interested in RUID (because the class CONSUMER_DETAILS2 doesn't include a field for this XML element), and also that the field NATIONALITY is not going to be loaded from this XML.
If the input XML of the question were in a file named input2.xml, then I'd have the following Java classes:
DataPacket
package test;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlAccessorType(XmlAccessType.NONE)
#XmlRootElement(name = "DATAPACKET")
public class DataPacket {
#XmlAttribute(name = "REQUEST_ID")
private int REQUEST_ID;
#XmlElement(name ="BODY")
private Body BODY;
public DataPacket(){}
public int getREQUEST_ID() {
return REQUEST_ID;
}
public void setREQUEST_ID(int REQUEST_ID) {
this.REQUEST_ID = REQUEST_ID;
}
public Body getBODY() {
return BODY;
}
public void setBODY(Body BODY) {
this.BODY = BODY;
}
}
Body
package test;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
#XmlAccessorType(XmlAccessType.NONE)
class Body {
#XmlElement(name = "CONSUMER_PROFILE2")
private ConsumerProfile profile;
public Body(){}
public ConsumerProfile getProfile() {
return profile;
}
public void setProfile(ConsumerProfile profile) {
this.profile = profile;
}
}
ConsumerProfile
package test;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
#XmlAccessorType(XmlAccessType.NONE)
public class ConsumerProfile {
#XmlElement(name = "CONSUMER_DETAILS2")
private ConsumerDetails CONSUMER_DETAILS2;
#XmlElement(name = "ID_DETAILS2")
private IdDetails ID_DETAILS2;
public ConsumerProfile(){}
public ConsumerDetails getCONSUMER_DETAILS2() {
return CONSUMER_DETAILS2;
}
public void setCONSUMER_DETAILS2(ConsumerDetails cONSUMER_DETAILS2) {
CONSUMER_DETAILS2 = cONSUMER_DETAILS2;
}
public IdDetails getID_DETAILS2() {
return ID_DETAILS2;
}
public void setID_DETAILS2(IdDetails iD_DETAILS2) {
ID_DETAILS2 = iD_DETAILS2;
}
}
ConsumerDetails
package test;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
#XmlAccessorType(XmlAccessType.NONE)
class ConsumerDetails {
#XmlElement(name="NAME")
private String NAME;
#XmlElement(name="DATE_OF_BIRTH")
private String DATE_OF_BIRTH;
#XmlElement(name="GENDER")
private String GENDER;
private String NATIONALITY;
public ConsumerDetails(){}
public String getNAME() {
return NAME;
}
public void setNAME(String nAME) {
NAME = nAME;
}
public String getDATE_OF_BIRTH() {
return DATE_OF_BIRTH;
}
public void setDATE_OF_BIRTH(String dATE_OF_BIRTH) {
DATE_OF_BIRTH = dATE_OF_BIRTH;
}
public String getGENDER() {
return GENDER;
}
public void setGENDER(String gENDER) {
GENDER = gENDER;
}
public String getNATIONALITY() {
return NATIONALITY;
}
public void setNATIONALITY(String nATIONALITY) {
NATIONALITY = nATIONALITY;
}
}
IdDetails
package test;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
#XmlAccessorType(XmlAccessType.NONE)
class IdDetails {
#XmlElement(name="SLNO")
private int SLNO;
#XmlElement(name="SOURCE_ID")
private String SOURCE_ID;
#XmlElement(name="ID_VALUE")
private int ID_VALUE;
#XmlElement(name="EXP_DATE")
private String EXP_DATE;
public IdDetails(){}
public int getSLNO() {
return SLNO;
}
public void setSLNO(int SLNO) {
this.SLNO = SLNO;
}
public String getSOURCE_ID() {
return SOURCE_ID;
}
public void setSOURCE_ID(String SOURCE_ID) {
this.SOURCE_ID = SOURCE_ID;
}
public int getID_VALUE() {
return ID_VALUE;
}
public void setID_VALUE(int ID_VALUE) {
this.ID_VALUE = ID_VALUE;
}
public String getEXP_DATE() {
return EXP_DATE;
}
public void setEXP_DATE(String EXP_DATE) {
this.EXP_DATE = EXP_DATE;
}
}
Also, inside the same "test" package the jaxb.index file with:
DataPacket
ConsumerProfile
ConsumerDetails
IdDetails
Then, when testing with this Test class:
package test;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
public class Test {
public static void main(String[] args) {
try{
JAXBContext jc = JAXBContext.newInstance(DataPacket.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("input2.xml");
DataPacket dp = (DataPacket) unmarshaller.unmarshal(xml);
Body body = dp.getBODY();
ConsumerProfile profile = body.getProfile();
ConsumerDetails consumerDetail = profile.getCONSUMER_DETAILS2();
IdDetails idDetails = profile.getID_DETAILS2();
System.out.println("ConsumerDetails name:"+consumerDetail.getNAME()+
" date of birth:"+consumerDetail.getDATE_OF_BIRTH()+
" gender:"+consumerDetail.getGENDER()+
"IdDetails SLNO:"+idDetails.getSLNO()+
" SOURCE_ID:"+idDetails.getSOURCE_ID()+
" ID_VALUE:"+idDetails.getID_VALUE()+
" EXP_DATE:"+idDetails.getEXP_DATE());
}
catch(JAXBException e){
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
I have the following XML:
<game name="m1itskow" sourcefile="maygay1bsw.c" ismechanical="yes" cloneof="m1itsko" romof="m1itsko">
<description>It's A Knockout (Maygay) (M1A/B) (set 24)</description>
<year>199?</year>
<manufacturer>Maygay</manufacturer>
</game>
Today I have manufacturer as a String inside Game class, but I need to map to a Manufacturer class, how should I do it? Is it possible? thanks.
edit: The XML cannot be changed because this is a generated file by a 3rd party tool.
Made changes in xml structure
XML
<?xml version="1.0" encoding="UTF-8"?>
<game name="m1itskow" sourcefile="maygay1bsw.c" ismechanical="yes" cloneof="m1itsko" romof="m1itsko">
<description>It's A Knockout (Maygay) (M1A/B) (set 24)</description>
<year>199?</year>
<manufacturer>
<manufacturer-name>Maygay</manufacturer-name>
</manufacturer>
</game>
POJO game and manufacturer...
game.java
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class game {
private String name;
private String sourcefile;
private String ismechanical;
private String cloneof;
private String romof;
private String description;
private String year;
private Manufacturer manufacturer=new Manufacturer();
public game() {}
#XmlAttribute
public String getIsmechanical() {
return ismechanical;
}
public void setIsmechanical(String ismechanical) {
this.ismechanical = ismechanical;
}
#XmlAttribute
public String getCloneof() {
return cloneof;
}
public void setCloneof(String cloneof) {
this.cloneof = cloneof;
}
#XmlAttribute
public String getRomof() {
return romof;
}
public void setRomof(String romof) {
this.romof = romof;
}
#XmlAttribute
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#XmlAttribute
public String getSourcefile() {
return sourcefile;
}
public void setSourcefile(String sourcefile) {
this.sourcefile = sourcefile;
}
#XmlElement
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#XmlElement
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
#XmlElement(name="manufacturer")
public Manufacturer getManufacturer() {
return manufacturer;
}
public void setManufacturer(Manufacturer manufacturer) {
this.manufacturer=manufacturer;
}
}
manufacturer.java
i
mport java.io.Serializable;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name="manufacturer")
public class Manufacturer implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String Name;
#XmlElement(name="manufacturer-name")
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
}
main.java
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
public class SampleTest {
public static void main(String[] args) {
try {
File file = new File("employee.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(game.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
game e=(game) jaxbUnmarshaller.unmarshal(file);
System.out.println(e.getManufacturer().getName());
}
catch (JAXBException e) {
e.printStackTrace();
}
}
}