I need to save some variables in a simple class using Java's XML Annotations: http://download.oracle.com/javase/6/docs/api/javax/xml/bind/annotation/package-summary.html
Currently the class is pretty simple and looks like this:
#XmlRootElement
public class Chart {
#XmlElement
public String url;
#XmlElement
public String values;
#XmlElement
public String projectOrFilterName;
#XmlElement
public String countComplains;
public Chart(String url, String values, String projectOrFilterName, String countComplains) {
this.url = url;
this.values = values;
this.projectOrFilterName = projectOrFilterName;
this.countComplains = countComplains;
}
}
Now I need to save the data of a list as string variables with annotations like the existing ones. Im giving the constructor some kind of a list, let's say
List<Object>
The question is, how to extract all the variables out of it, and save their toString() representations with the given XML Annotations. If that's simpler one could assume, I get a List of Strings.
Can somebody please help me with this?
Who could have known, it would be that simple ;-)
#XmlElement
public List<String> data;
That's just, what I needed. The java script part, interpreting the xml creates an array out of the list's elements and everything is fine.
Thanks for your time thinking over my question!
Related
I want to unmarshall a XML-File with mixed Content. I found a thread on stackoverflow which seemed appropriate (JAXB- #XmlMixed usage for reading #XmlValue and #XmlElement) where the user bdoughan defined 3 Use-Cases to deal with mixed content.
The third use case would keep the text between the tags in a single String variable and save the elements in a List. Which is what I wanted. Unfortunately I couldn't get it to work and the thread is quite old and maybe outdated.
I've tried the Usecase #3 with a List of Objects and a List of my Reference Class. Also I tried #XmlElement and #XmlValue Annotations.
I'm using the javax.xml.bind jaxb-api in version 2.3.1 and the org.glassfish.jaxb jaxb-runtime in version 2.3.1 in a Maven Projec with Java SE Version 12.0.2.
A Sample XML I tested with
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Date>
2018.06.27
<reference id="AnyId1">
</reference>
</Date>
My Class Representation
#XmlRootElement(name="Date")
public class TestPojo {
#XmlMixed
public String getTextContent() {
return textContent;
}
public void setTextContent(String textContent) {
this.textContent = textContent;
}
#XmlElementRef(name="reference", type = Reference.class)
public List<Object> getRef() {
return ref;
}
public void setRef(List<Object> ref) {
this.ref = ref;
}
String textContent;
List<Object> ref = new ArrayList<Object>();
}
I'd expect that the xml is unmarshalled into a POJO object and the right values are assigned. The Objects variables (textContent & ref) are null after unmarshalling.
You could try this:
Using a Reference class as below,
#XmlAccessorType(XmlAccessType.FIELD)
public class Reference {
#XmlAttribute
private String id;
}
And your Root class,
#XmlRootElement(name="Date")
public class TestPojo {
#XmlMixed
#XmlAnyElement
private List<Object> textContent;
#XmlElement
private Reference reference;
}
This will unmarshall giving you the reference element and everything else in a List.
For the example you have it will be 2 entries. The date value/text along with tab character (\t) and new line characters (\n), and another entry with new line character.
So you can use this list to process the contents and use what you want.
If there is a cleaner solution, I am interested. Cheers
Update to answer to comment:
In order to be more clear with the fix. What I did was using #XmlElement instead of #XmlElementRef for a single Reference instead of list (cos that's what I saw in the xml).
Also I added the #XmlAnyElement annotation for the mixed content made it a list. This is what fixed it. So sticking with your class, it would look like below:
#XmlRootElement(name="Date")
public class TestPojo {
List<Object> textContent;
Reference ref;
#XmlMixed
#XmlAnyElement
public List<Object> getTextContent() {
return textContent;
}
public void setTextContent(List<Object> textContent) {
this.textContent = textContent;
}
#XmlElement(name="reference")
public Reference getRef() {
return ref;
}
public void setRef(Reference ref) {
this.ref = ref;
}
}
The #XmlAccessorType saved me time from writing getters and setters. For an explanation of what this annotation does with an example (and in relation to #XmlElement, check this:
What is the difference between using #XmlElement before field and before getter declaration?
I have to call a webservice, that takes only one argument, but that argument should contain three values(UserName,Password,company) inside it. How can I achieve this in Java?
The "Java" way of doing this would be to construct a class that wraps these three values:
public class UserData {
private String username;
private String password;
private String company;
/* Constructor from the three parameters, getters, and possibly setters */
}
If you don't want to go through the hassle of creating a specific class for it, you could use some other, more generic, container, such as Apache Commons Lang's Triple.
Depending on the webservice method, this solution covers REST webservices.
This is a GET example.
#GET
#Path("/{id}/{name}")
#Produces({MediaType.APPLICATION_XML})
public Person fetchPerson(
#PathParam("id") Integer id,
#PathParam("name") String name) {
I have a base class that I want to convert. All the types I want to convert to are identical to each other, except for the package name. They're created in specs I have no control over. Is there a way of creating a generic converter, so I'm not repeating identical get and set calls over and over? Mine are obviously more complex than the ones below, but the point I'm highlighting is that the field names differ between the original and final types.
Original:
com.mycompany.base.ConvertMe;
class ConvertMe {
private String name;
private String colour;
private String fruit;
//getters and setters...
}
Needs to map to:
com.mycompany.convertedA;
class Result {
private String firstName;
private String favouriteColour;
private String favouriteFruit;
//getters and setters...
}
And also map to:
com.mycompany.convertedB;
class Result {
private String firstName;
private String favouriteColour;
private String favouriteFruit;
//getters and setters...
}
Dozer is what you are looking for. It is very flexible and convenient for those cases, as supports mappings via annotations, xml mappings.
Orika could be another option. Though Dozer is one of the powerful and simplest.
For more detailed comparison, check this post
Jersey by default convert single element returned to object . But the client side is expecting the data in json to be arraylist
Model class is LocationDetails
public class LocationDetails {
private String locationAccount;
private String locationName;
private String locationStreet;
private String locationPostcode;
}
other class LocationData which has arraylist of LocationDetails as
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class LocationData {
private ArrayList<LocationDetails> Locations;
}
and the controller class is using the following code to convert to JSON:
//Getting location and item along with barcodes
#POST
#Path("/getLocationAndItemData")
#Produces(MediaType.APPLICATION_JSON)
public LocationResponse getAlllocations(){
ArrayList<LocationDetails> locationDetailList = new ArrayList<LocationDetails>();
LocationDetails details = new LocationDetails();
//setting location account
details.setLocationAccount("10125");
locationDetailList.add(details);
}
The following code is returning json as LocationData : {LocationDetails : {"LocationAccount","10125"}}
whereas i want it to be like :
LocationData : {LocationDetails : [{"LocationAccount","10125"}]}
as the client side would expect the data to be inside list.
How to convert the type without changing the whole logic.I am using jersey.
Add #XmlElementWrapper annotation to your List, that should do the trick. If you have further problems with Jersey, try first XML output to see what is being produced. If XML is ok, JSON will be too.
#XmlElement(name="locationDetail")
#XmlElementWrapper(name="locationDetails")
private List<LocationDetail> locationDetails;
Also name your class properties with first lowercase letter, please.
I too had the same issue, after so many research i found that the problem is due to the jar files imported in the MyEclipse (Persisted container). I have removed that. The same code works for me.
The json format will be [{single element}].
I want to create one XML file from one list of objects. Objects are having some attributes, so the tags will be the attribute names and the respective data will be inside the tag.
This is example:
I have one List myEquipmentList, that contains 100 objects of the class Equipment. Now, the attributes in the class of Equipment are id, name, size, measures, unit_of_measure etc.
Now I want to create XML which will be something like this.
<Equipment id=1>``
<name>Ruler</name>
<size>1000</size>
<measures>length</measures>
<unit_of_measure>meter</unit_of_measure>
</Equipment>
Any ideas?
you can create a class with the list of objects, then serialise the list to xml and finally deserialise xml to a list.
Please see this link - Very useful:
How to convert List of Object to XML doc using XStream
Read about JAXB.
You could have a class like this that would generate the XML you want:
#XmlRootElement
public class Equipment {
private Long id;
private String name;
private Integer size;
...etc...
#XmlAttribute
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#XmlElement
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
... etc...
}
You'll find plenty of info on JAXB on google on searching on stackoverflow.
http://jaxb.java.net/
http://jaxb.java.net/tutorial/
These look like a couple of simple tutorials:
http://www.mkyong.com/java/jaxb-hello-world-example/
http://www.vogella.com/articles/JAXB/article.html
One of the easiest ways to do this is simply iterate over the list and use strings to write the XML. Nothing special, very quick and easy.
I tend to use a library called Simple XML Serialization over JAXB, and I have to say it's pretty simple, yet extremely flexible.
There's good comparison between Simple and JAXB here.