I've been doing a lot of solutions, but noone does it work. How can i print this XML code in java. The main problem is how can I print value xml:lang.
<resource xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ofbiz.apache.org/dtds/ofbiz-properties.xsd">
<property key="hour.plural">
<value xml:lang="ar">ساعات</value>
<value xml:lang="de">Stunden</value>
<value xml:lang="pl">oglądaj</value></property></resource>
It's the resource class
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name="resource")
public class resource {
private String property;
private String value;
public root(String property, String value) {
this.property = property;
this.value = value;
}
public String getProperty() {
return property;
}
public String getValue() {
return value;
}
public String toString() {
return property + value;
}
}
And that's the main class
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import project1.resource;
public class xmlread {
public static void main(String... arg) throws Exception {
File file = new File("C:DateTimeLabels.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(resource.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
resource Resource = (resource) jaxbUnmarshaller.unmarshal(file);
System.out.println(Resource);
}
}
#XmlRootElement(name="resource")
public class resource {
private String property;
private String value;
public root(String property, String value) {
this.property = property;
this.value = value;
}
#XmlElement(name = "property")
public String getProperty() {
return property;
}
#XmlElement(name = "value")
public String getValue() {
return value;
}
public String toString() {
return property + value;
}
}`
Add this to your resource class, should help the marshaller find the exact properties you want.
You have more than one value, so for the sake of the <value> elements, you need to define a list of values.
The elements are contained inside the elements, so you have a nested structure here. That means you need a Property class contained in your Resource class, and your Property class need to contain a Value class.
You need to bind the key attribute and the xml:lang attributes.
Here is an example of Jaxb-annotated classes that does most of the work to map to your XML format. Complete as you need.
#XmlRootElement
public class Resource {
private Property property = new Property();
public Property getProperty() {
return property;
}
public void setProperty(Property property) {
this.property = property;
}
public static void main(String[] args) throws JAXBException {
JAXBContext context = JAXBContext.newInstance(Resource.class);
Marshaller marshaller = context.createMarshaller();
Resource resource = new Resource();
resource.getProperty().setKey("hour.plural");
resource.getProperty().getValues().add(new Value("fr"));
resource.getProperty().getValues().add(new Value("it"));
resource.getProperty().getValues().add(new Value("ru"));
marshaller.marshal(resource, System.out);
}
}
class Property {
private String key;
private List<Value> values = new ArrayList<>();
#XmlAttribute
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
#XmlElement(name = "value")
public List<Value> getValues() {
return values;
}
public void setValues(List<Value> values) {
this.values = values;
}
}
class Value {
private String lang;
public Value() {
}
public Value(String lang) {
this.lang = lang;
}
#XmlAttribute
public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang = lang;
}
}
Related
How do I get Jackson to treat 'name' as if it had a #JsonProperty annotation?
public class SimpleClass {
private String name;
private String doNotSerialize;
public SimpleClass( #JsonProperty("name") String name ) {
this.name = name;
}
public String getName() {
return name;
}
public int getSum() {
return 1+1;
}
}
The way it is now, I get an error, Unrecognized field "sum", because it treats every getter as a serializable property.
If I add a class annotation:
#JsonAutoDetect( getterVisibility = JsonAutoDetect.Visibility.NONE )
I get an empty string when serializing. I was hoping that Jackson would see the #JsonProperty on the constructor parameter and figure it out.
If I change the class annotation to:
#JsonAutoDetect( getterVisibility = JsonAutoDetect.Visibility.NONE, fieldVisibility = JsonAutoDetect.Visibility.ANY )
Then I get the 'doNotSerialize' field included.
If I set a #JsonCreator on the constructor, and change my autodetect, I still get a blank string:
#JsonAutoDetect( getterVisibility = JsonAutoDetect.Visibility.NONE, fieldVisibility = JsonAutoDetect.Visibility.NONE, creatorVisibility = JsonAutoDetect.Visibility.ANY )
public class SimpleClass {
private String name;
private String doNotSerialize;
#JsonCreator
public SimpleClass( #JsonProperty("name") String name ) {
this.name = name;
}
public String getName() {
return name;
}
public int getSum() {
return 1+1;
}
}
What I'm hoping is that somehow I can tell Jackson to treat all the constructor parameters as serializable fields, and all other fields / setters as non-serializable.
You can use a filter to only serialise getters which have a matching field, e.g.
package org.example;
import com.fasterxml.jackson.annotation.JsonFilter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.PropertyWriter;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import java.io.IOException;
import java.io.StringWriter;
public class App {
#JsonFilter("test")
public static class SimpleClass {
private String name;
private String doNotSerialize;
public SimpleClass(String name ) {
this.name = name;
}
public String getName() {
return name;
}
public int getSum() {
return 1+1;
}
}
public static void main( String[] args ) throws IOException {
SimpleFilterProvider filterProvider = new SimpleFilterProvider();
filterProvider.addFilter("test", new SimpleBeanPropertyFilter() {
#Override
protected boolean include(BeanPropertyWriter writer) {
return super.include(writer);
}
#Override
protected boolean include(PropertyWriter writer) {
String name = writer.getName();
Class clazz = writer.getMember().getDeclaringClass();
try {
clazz.getDeclaredField(name);
return super.include(writer);
} catch (NoSuchFieldException e) {
// ignore
return false;
}
}
});
ObjectMapper mapper = new ObjectMapper();
mapper.setFilterProvider(filterProvider);
StringWriter sw = new StringWriter();
mapper.createGenerator(sw).writeObject(new SimpleClass("foo"));
System.out.println(sw.toString());
}
}
I don't know your full requirements, but this should be a start.
I haven't tried to do what you actually, asked, that is, look at constructor parameters, but that should be possible too.
If you want "sum" to be included in the serializad json but want to ignore it when deserializing you can do:
#JsonIgnoreProperties(ignoreUnknown=true)
public class SimpleClass {
// properties/getters
public int getSum() { return 1+1; }
}
If you want to remove "sum" entirely from the json you can do
#JsonIgnoreProperties({"sum"})
public class SimpleClass {
// properties/getters
public int getSum() { return 1+1; }
}
or
public class SimpleClass {
// properties/getters
#JsonIgnore
public int getSum() { return 1+1; }
}
I create an java class:
public class ReturnObj {
private String returncode;
private String returndesc;
private Pkg pkg;
public String getReturncode() {
return returncode;
}
public void setReturncode(String returncode) {
this.returncode = returncode;
}
public String getReturndesc() {
return returndesc;
}
public void setReturndesc(String returndesc) {
this.returndesc = returndesc;
}
}
and other class:
public class Pkg {
private String packagecode;
private String cycle;
private String price;
private String desc;
public String getPackagecode() {
return packagecode;
}
public void setPackagecode(String packagecode) {
this.packagecode = packagecode;
}
public String getCycle() {
return cycle;
}
public void setCycle(String cycle) {
this.cycle = cycle;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
And I Want to convert object ReturnObj to this XML
<return>
<returncode>1</returncode>
<returndesc>DANG_KY_THANH_CONG</returndesc>
<package>
<packagecode>BD30</packagecode>
<cycle>1</cycle>
<price>15000</price>
<desc> BD30</desc>
</package>
</return>
So how do I serialize an attribute pkg to package in XML? Because Java doesn't allow to name variable as an keyword anh package is an keyword in Java !
You can use JAXB marshling in your class it will convert the object to XML, here is link to help you JAXB Marshling
Try xstream
XStream xstream = new XStream();
xstream.alias("package", Pkg.class);
String xml = xstream.toXML(myReturnObj);
You can use JAXB API that comes with java for converting java object to XML.
Below is the code that will solve your requirement.
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "return")
public class ReturnObj {
private String returncode;
private String returndesc;
private Pkg pkg;
public Pkg getPkg() {
return pkg;
}
#XmlElement(name = "package")
public void setPkg(Pkg pkg) {
this.pkg = pkg;
}
public String getReturncode() {
return returncode;
}
#XmlElement(name = "returncode")
public void setReturncode(String returncode) {
this.returncode = returncode;
}
public String getReturndesc() {
return returndesc;
}
#XmlElement(name = "returndesc")
public void setReturndesc(String returndesc) {
this.returndesc = returndesc;
}
}
#XmlRootElement
public class Pkg {
private String packagecode;
private String cycle;
private String price;
private String desc;
public String getPackagecode() {
return packagecode;
}
#XmlElement(name="packagecode")
public void setPackagecode(String packagecode) {
this.packagecode = packagecode;
}
public String getCycle() {
return cycle;
}
#XmlElement(name="cycle")
public void setCycle(String cycle) {
this.cycle = cycle;
}
public String getPrice() {
return price;
}
#XmlElement(name="price")
public void setPrice(String price) {
this.price = price;
}
public String getDesc() {
return desc;
}
#XmlElement
public void setDesc(String desc) {
this.desc = desc;
}
}
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class JAXBExample {
private static final String FILE_NAME = "C:\\ru\\jaxb-returnObj.xml";
public static void main(String[] args) {
ReturnObj returnObj = new ReturnObj();
returnObj.setReturncode("1");
returnObj.setReturndesc("DANG_KY_THANH_CONG");
Pkg pkg = new Pkg();
pkg.setCycle("1");
pkg.setPrice("15000");
pkg.setDesc("BD30");
returnObj.setPkg(pkg);
jaxbObjectToXML(returnObj);
}
private static void jaxbObjectToXML(ReturnObj emp) {
try {
JAXBContext context = JAXBContext.newInstance(ReturnObj.class);
Marshaller m = context.createMarshaller();
// for pretty-print XML in JAXB
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
// Write to System.out, this will print the xml on console
m.marshal(emp, System.out);
// Write to File
m.marshal(emp, new File(FILE_NAME));
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
Explanation:
#XmlRootElement: This is a must have annotation for the Object to be used in JAXB. It defines the root element for the XML content.
#XmlElement: This will create the element. If you want to give some other name to the xml element when converting java object to xml then you can pass name attribute to the #XmlElement Example:
#XmlElement(name = "package")
Execute above code to see the desired output.
Happy Coding.
I have an xml file with data (not complete xml file)
<header>
<ParameterContext>
<Parameter>
<Name>FILEID<Name>
<Value>1001445<Value>
</Parameter>
<Identifier>Id</Identifier>
</ParameterContext>
<ParameterContext>
<Parameter>
<Name>product</Name>
<Value>ECT</ns0:Value>
</Parameter>
<Identifier>ProductName</Identifier>
</ParameterContext>
</header>
please help me to store this xml data(data of parametercontext elements) in to arraylist.
Sorry for not posting this earlier.
I have 2 classes object and load
public class object{
private ArrayList<ParameterContext> parameterCtx = new ArrayList<ParameterContext>();
public ArrayList<ParameterContext> getParameterCtx() {
return parameterCtx;
}
public void setParameterCtx(ParameterContext parameterCtx) {
this.parameterCtx.add(parameterCtx) ;
}
public Parameter searchParameter(String name, String identifier, ArrayList<ParameterContext> al) {
for(int i = 0; i < al.size(); i++) {
if(al.get(i).getIdentifier().equalsIgnoreCase(identifier)) {
for(int j = 0; j < al.get(i).getParameter().size(); j++) {
if(al.get(i).getParameter().get(j).getName().equalsIgnoreCase(name) ) {
return al.get(i).getParameter().get(j);
}
}
}
}
return null ;
}
}
and
public class load{
#XmlElement(name = "ParameterContext")
protected List<load.ParameterContext> parameterContext;
public List<load.ParameterContext> getParameterContext() {
if (parameterContext == null) {
parameterContext = new ArrayList<load.ParameterContext>();
}
return this.parameterContext;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"parameter",
"identifier"
})
public static class ParameterContext {
#XmlElement(name = "Parameter", required = true)
protected List<load.ParameterContext.Parameter> parameter;
#XmlElement(name = "Identifier", required = true)
protected String identifier;
public List<load.ParameterContext.Parameter> getParameter() {
if (parameter == null) {
parameter = new ArrayList<load.ParameterContext.Parameter>();
}
return this.parameter;
}
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String value) {
this.identifier = value;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"name",
"value"
})
public static class Parameter {
#XmlElement(name = "Name", required = true)
protected String name;
#XmlElement(name = "Value", required = true)
protected String value;
public String getName() {
return name;
}
public void setName(String value) {
this.name = value;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
when i use object.searchparameter("FIELD","ID",object.getParameterCtx()).getValue());
NULLPOINTEREXCEPTION is coming.(getparameterCtx is not initialized).Before this line I need to initialize it right.How to Initialize?
using JAXB, create a class that mimics the XML
#XmlRootElement(name="header")
public class XMLBean {
public List<ParameterContext> pc;
public XMLBean() {
}
public List<ParameterContext> getPc() {
return pc;
}
public void setPc(List<ParameterContext> pc) {
this.pc = pc;
}
}
public class ParameterContext {
public Parameter parameter;
public String identifier;
public ParameterContext() {
}
public Parameter getParameter() {
return pc;
}
public void setParameter(Parameter parameter) {
this.param = param;
}
public String getIdentifier() {
return identifer;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
}
public class Parameter {
public String name;
public String value;
public Parameter() {
}
public void setName(String name) {
this.name = name;
}
public void getName() {
return name;
}
public void setValue(String value) {
this.value = value;
}
public void getValue(String value) {
return value;
}
}
public static void main(String[] args) {
InputStream is = YOURXML
JAXBContext jaxb = JAXBContext.newInstace(XMLBean.class);
Unmarshaller jaxbUnmarshaller = jaxb.createUnmarshaller();
XMLBean xml = (XMLBean) jaxbUnmarshaller.unmarshal(is);
System.out.println(xml.getParameterContext().get(0).getParam().getName());
System.out.println(xml.getParameterContext().get(0).getParam().getValue());
}
something like that
If the xml elements are same and repetitive Create an object with the attributes as the elements with getter/setters. Parse the xml data and store the value in the object.
I can marshall a ObservableList using a "Wrapper"-class like below. But I cannot unmarshall it back to the wrapperclass it was before.
The idea is:
I have an ObservableList of "Expenses". I put this List into a wrapper-class and save this class to XML. The result looks like this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<List>
<root>
<category>[none]</category>
<period>Year</period>
<title>asd</title>
<value>354</value>
</root>
</List>
I cannot bring it back to the wrapper-object.
I really appreciate any kind of help.
Main-class JAXBContext (visible for all):
JAXBContext jc = JAXBContext.newInstance(MyWrapperForList.class, Expense.class);
Main-class SAVEBUTTON:
public class SaveButtonListener implements EventHandler<ActionEvent> {
#Override
public void handle(ActionEvent arg0) {
File serializedFile = new File(PATH);
try {
if (serializedFile.exists() == false)
serializedFile.createNewFile();
PrintWriter xmlOut = new PrintWriter(serializedFile);
Marshaller m = jc.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
List<Expense> saveList = new ArrayList<>();
saveList.addAll(data);
MyWrapperForList<Expense> wrapper = new MyWrapperForList<>(saveList);
JAXBElement<MyWrapperForList> jaxbElement = new JAXBElement<>(
new QName("List"), MyWrapperForList.class, wrapper);
m.marshal(jaxbElement, xmlOut);
xmlOut.flush();
xmlOut.close();
Main-class-LOADBUTTON:
public class LoadButtonListener implements EventHandler<ActionEvent> {
#Override
public void handle(ActionEvent arg0) {
try {
Unmarshaller unmarshaller = jc.createUnmarshaller();
StreamSource xml = new StreamSource(PATH);
MyWrapperForList<Expense> unwrapper = unmarshaller.unmarshal(xml,
MyWrapperForList.class).getValue();
List<Expense> tempList = new ArrayList<>();
tempList.addAll(unwrapper.getItems());
System.out.println(tempList.get(0).getTitle());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Wrapper-class:
public class MyWrapperForList {
private List<Expense> list;
public MyWrapperForList() {
list = new ArrayList<>();
}
public MyWrapperForList(List<Expense> expenses) {
this.list = expenses;
}
#XmlAnyElement(lax=true)
public List<Expense> getItems() {
return list;
}
}
Expense-class:
#XmlRootElement(name = "root")
public class Expense {
private String title;
private String category;
private String period;
private String value;
public Expense() {} //Default constructor is needed for XML-handling
public Expense(String title, String value, String period, String category) {
this.title = title;
this.value = value;
this.period = period;
this.category = category;
}
#XmlElement(name = "title")
public String getTitle() {
return this.title;
}
#XmlElement(name = "category")
public String getCategory() {
return this.category;
}
#XmlElement(name = "period")
public String getPeriod() {
return this.period;
}
#XmlElement(name = "value")
public String getValue() {
return this.value;
}
}
I used this tutorial from Blaise Doughan: http://blog.bdoughan.com/2012/11/creating-generic-list-wrapper-in-jaxb.html
MyListWrapper
If you want MyWrapperForList to unmarshal holding an instance of ObservableList then you will need to setup your class in one of the following ways.
Property of Type ObservableList
import javax.xml.bind.annotation.XmlAnyElement;
import javafx.collections.*;
public class MyWrapperForList<T> {
private ObservableList<T> list;
public MyWrapperForList() {
list = FXCollections.<T>observableArrayList();
}
public MyWrapperForList(ObservableList<T> list) {
this.list = list;
}
#XmlAnyElement(lax = true)
public ObservableList<T> getItems() {
return list;
}
}
List Property Initialized to Instance of ObservableList
import java.util.List;
import javax.xml.bind.annotation.XmlAnyElement;
import javafx.collections.*;
public class MyWrapperForList<T> {
private List<T> list = FXCollections.<T>observableArrayList();
public MyWrapperForList() {
list = FXCollections.<T>observableArrayList();
}
public MyWrapperForList(List<T> list) {
this.list = list;
}
#XmlAnyElement(lax = true)
public List<T> getItems() {
return list;
}
}
Demo Code
Input (nub.xml)
<List>
<root>
<category>[none]</category>
<period>Year</period>
<title>dfg</title>
<value>4</value>
</root>
<root>
<category>[none]</category>
<period>Year</period>
<title>ROBO</title>
<value>1234</value>
</root>
</List>
Demo
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(MyWrapperForList.class, Expense.class);
//UNMARSHALLING
Unmarshaller unmarshaller = jc.createUnmarshaller();
StreamSource xml = new StreamSource("src/forum18594548/nub.xml");
MyWrapperForList<Expense> wrapper = (MyWrapperForList<Expense>) unmarshaller.unmarshal(xml, MyWrapperForList.class).getValue();
List<Expense> data = wrapper.getItems();
System.out.println(data.getClass());
for(Expense expense : data) {
System.out.println(expense);
}
}
}
Output
class com.sun.javafx.collections.ObservableListWrapper
forum18594548.Expense#789df61d
forum18594548.Expense#4a8927c8
UPDATE
First: Thanks for you work Blaise!! I'm really glad for what you do to
me! I tried what you wrote here (it was nearly the same as I had) and
I got a similar (same type of) output as you got. BUT the objects in
the lists are all referenced with null. If I write
System.out.println(data.get(0).getTitle()); it says null. There is the
exact amount of objects in the list, but all attributes are referenced
with null. :(
I think I got tunnel vision on the ObservableList aspect only to miss your real problem was with how you mapped the Expense class. Since you only have get methods you should map to the fields using #XmlAccessorType(XmlAccessType.FIELD) as follows.
import javax.xml.bind.annotation.*;
#XmlRootElement(name="root")
#XmlAccessorType(XmlAccessType.FIELD)
public class Expense {
private String title;
private String category;
private String period;
private String value;
public Expense() {
}
public Expense(String title, String value, String period, String category) {
this.title = title;
this.value = value;
this.period = period;
this.category = category;
}
public String getTitle() {
return this.title;
}
public String getCategory() {
return this.category;
}
public String getPeriod() {
return this.period;
}
public String getValue() {
return this.value;
}
}
I have an issue. I want to convert an object into another object using JAXB. As in, I have a class com.home.Student, and another class com.school.Student, both have same arguments, in fact both are same (copy paste), but different package. I want to perform the conversion between them using JAXB.
How to do that, please help me.
It would be nice if you included some code that explains your problem.
JAXB 101 says you should place the right annotations, then you can serialize and deserialize correctly. You should properly annotate your classes with #XmlRootElement, #XmlElement, #XmlAttribute, etc
For example:
#XmlRootElement(name="student")
#XmlAccessorType(XmlAccessType.NONE)
class Student {
#XmlElement(name="name")
private String name;
#XmlElement(name="age")
private int age;
public Student() {
}
public String getName() { return name; }
public int getAge() { return age; }
}
Then you can use serialize it using JAXB Marshaller:
StringWriter writer = new StringWriter();
JAXBContext context = JAXBContext.newInstance(Student.class);
Marshaller m = context.createMarshaller();
m.marshal(student, writer);
And deserialize it as well by Unmarshelling the input ..
JAXBContext context = JAXBContext.newInstance(Student.class);
Unmarshaller m = context.createUnmarshaller();
return (Student)m.unmarshal(new StringReader(input));
Make sure you look at the JavaDoc I mentioned above since there are many ways to do so.
If you cannot modify your classes, you can still use JAXB (or you can use XStream) Assuming your class is the following:
class Student {
private String name;
private int age;
public Student() {
}
public void setName(String name) { this.name = name; }
public String getName() { return name; }
public void setAge(int age) { this.age = age; }
public int getAge() { return age; }
}
You can serialize it by doing:
Student student = new Student();
student.setAge(25);
student.setName('FooBar');
StringWriter writer = new StringWriter();
JAXBContext context = JAXBContext.newInstance(Student.class);
Marshaller m = context.createMarshaller();
m.marshal(new JAXBElement(new QName(Student.class.getSimpleName()), Student.class, student), writer);
System.out.println(writer.toString());
If you are using XStream, you can do the serialization without Annotations too (and it is more controllable).
http://x-stream.github.io/tutorial.html
You could do the following.
Note:
It does not require that you ever materialize the data as XML, by leveraging JAXBSource.
It does not require any annotations on your object model.
com.home.Student
package com.home;
public class Student {
private String name;
private Status status;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
}
com.home.Status
package com.home;
public enum Status {
FULL_TIME("F"),
PART_TIME("P");
private final String code;
Status(String code) {
this.code = code;
}
public String getCode() {
return code;
}
}
com.school.Student
package com.school;
public class Student {
private String name;
private Status status;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
}
com.school.Status
package com.school;
public enum Status {
FULL_TIME("F"),
PART_TIME("P");
private final String code;
Status(String code) {
this.code = code;
}
public String getCode() {
return code;
}
}
com.example.Demo;
package com.example;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.util.JAXBSource;
import javax.xml.namespace.QName;
public class Demo {
public static void main(String[] args) throws Exception {
com.home.Student studentA = new com.home.Student();
studentA.setName("Jane Doe");
studentA.setStatus(com.home.Status.FULL_TIME);
JAXBContext contextA = JAXBContext.newInstance(com.home.Student.class);
JAXBElement<com.home.Student> jaxbElementA = new JAXBElement(new QName("student"), com.home.Student.class, studentA);
JAXBSource sourceA = new JAXBSource(contextA, jaxbElementA);
JAXBContext contextB = JAXBContext.newInstance(com.school.Student.class);
Unmarshaller unmarshallerB = contextB.createUnmarshaller();
JAXBElement<com.school.Student> jaxbElementB = unmarshallerB.unmarshal(sourceA, com.school.Student.class);
com.school.Student studentB = jaxbElementB.getValue();
System.out.println(studentB.getName());
System.out.println(studentB.getStatus().getCode());
}
}
If your goal is simply to convert (assign actually) between the two, and they're identical except package name, I would think you could use simple reflection. Just iterate over the fields of source object, and assign to the field of the same name in the target object. Vaguely, like this:
import java.lang.reflect.Field;
public class Converter {
public void convert (com.home.Student src, com.school.Student dst) throws Exception {
for (Field f : src.getFields()) {
// src field name
String name = f.getName();
// get corresponding field in dst
Field dstField = dst.getDeclaredField(name);
dstField.set(dst, f.get());
}
}
}
Note: I didn't compile this, which is why I say "vaguely". You'll need to use the Field.isAccessible()/Field.setAccessible(true) if the fields are private, so that you can temporarily change accessibility while you're assigning values. Or, you an write slightly more complex code that uses public setters/getters rather than directly using field access.