xml to json using JAXB AND JAXRS?

hi,

I am trying to understand how JAXRS knows to call(map) a method in the POJO model to create a property (field) in the json data.

Say I have the following xml and POJO:


XML Data:
....
<site>
   <name>Google</name>
   <uri>google.com/x121212</uri>
  </site>

Open in new window

POJO Model:
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "site")
public class Site {
	private String name;
	private String uri;

              String getName(){
                 return name;
               }
              void setName(String name){
              this.name=name;
            }
            String getUri() {
                return uri;
             }
             void setUri(String uri) {
                this.uri=uri;
}             
            String getId(){
                if (uri != null) {
			return uri.substring(uri.lastIndexOf("/") + 1);
		}
		return null;

          }
           String getCompanyType()
{
               return "Retail";
}

Open in new window

             

JSON I GOT:
[
{"name":"google","uri":"google.com/x121212", "id":"x121212","companType":"Retail"
 ]

Open in new window



JAX-RS/JAXB Call:
@Path("/site/{id}")
	@GET()
	@Produces("application/json")
	public Response getSite(@PathParam("id") String id) {
		Site site= null;
		try {
                                               //#1  I get my xml 
			String siteXML = service.site(id);
                                               //#2 convert xml to POJO object
			site = JaxBXMLToBean.convertToSite(siteXML);

		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return Response.status(500).build();
		} catch (Exception e) {
			e.printStackTrace();
			return Response.status(500).build();
		}
		return Response.status(200).entity(site).build();
	}

Open in new window



My question is how does the id and companyType gets to created in the JSON file?

I have been searching for document or tutorial explaining this but I must be googling for wrong words.
Can you help?
dkim18Asked:
Who is Participating?
 
mccarlConnect With a Mentor IT Business Systems Analyst / Software DeveloperCommented:
Here is a basic example of how JAX-RS (or more correctly, JAX-RS's JSON Provider which might be a library such as Jackson) might use reflection to take an object and automatically get all the fields (getters) and their values...
    public Map<String, Object> getFields(Object object) {
        Map<String, Object> result = new HashMap<String, Object>();
        
        for (Method method : object.getClass().getDeclaredMethods()) {
            try {
                String methodName = method.getName();
                if (methodName.startsWith("get")) {
                    String fieldName = methodName.substring(3, methodName.length());
                    Object fieldValue = method.invoke(object);
                    
                    result.put(fieldName, fieldValue);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        return result;
    }

Open in new window

You could pass an object of your type Site into the above and you would get four entries in the map just like the four items in the JSON data you posted above.
0
 
mrcoffee365Commented:
Does the above example work?  If so, I imagine that json fields are named the same as the xml tags, similarly to how bean get and set methods work.
0
 
dkim18Author Commented:
Yes the above code works.
My question is how does the pojo from the jabx know to call getId() and getCompanyType() to get the json data?
I guess this happens when the response tries to build a entity?


I am trying to understand how this gets handled by jaxrs?
0
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
dkim18Author Commented:
As i said, xml does not have id and companytype fields.
0
 
mrcoffee365Commented:
"As i said, xml does not have id and companytype fields. " -- didn't see where you said that.  Are you working on multiple questions at EE?  Perhaps you mentioned that elsewhere.

However, as I said, if you didn't have to write any code for this, then the calls are being made based on the names of the tags.
0
 
dkim18Author Commented:
Sorry  it looks i didnot mention it here about id and compantype elements not being in the xml.
The pojo model doesnot have the id property but only getId() method. it looks the http response object is calling that method from the http request because my json data has that id property.

I googled about it but cannot find any doc.
0
 
mrcoffee365Connect With a Mentor Commented:
Are you interested in how to create a method call based on a String name (which is what the program would get from the json file)?  Reflection is an interesting part of java, although most of the time we don't have to use it.  But tools like this do.

This is a discussion of how one sort of json reflection works:
https://blogs.oracle.com/arungupta/entry/json_binding_with_jax_rs
0
 
Mahesh BhutkarConnect With a Mentor Commented:
how does the id and companyType gets to created in the JSON file

getId(){ } & getCompanyType() methods are present inside you POJO class.

You can add one more getter method and execute to check the result.
0
 
dkim18Author Commented:
I know having the getXXxx() method will create the XXxx field in the json data.
How does the response class do this?
Is the reflection?
Do you know where i can read about it?
0
 
Mahesh BhutkarCommented:
Yes, it's a reflection only.


A getter method have its name start with "get", take 0 parameters, and returns a value.


You can checkout this rule in above your example.
0
 
mrcoffee365Commented:
You can search for java reflection, or read any good java book in the chapter on reflection.

Are you having a specific problem, and that's why you want to read about reflection?
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.