Solved

xml to json using JAXB AND JAXRS?

Posted on 2014-01-24
11
367 Views
Last Modified: 2014-02-06
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?
0
Comment
Question by:dkim18
  • 4
  • 4
  • 2
  • +1
11 Comments
 
LVL 27

Expert Comment

by:mrcoffee365
ID: 39808729
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
 

Author Comment

by:dkim18
ID: 39808744
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
 

Author Comment

by:dkim18
ID: 39808747
As i said, xml does not have id and companytype fields.
0
MIM Survival Guide for Service Desk Managers

Major incidents can send mastered service desk processes into disorder. Systems and tools produce the data needed to resolve these incidents, but your challenge is getting that information to the right people fast. Check out the Survival Guide and begin bringing order to chaos.

 
LVL 27

Expert Comment

by:mrcoffee365
ID: 39808750
"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
 

Author Comment

by:dkim18
ID: 39808776
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
 
LVL 27

Assisted Solution

by:mrcoffee365
mrcoffee365 earned 166 total points
ID: 39808808
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
 
LVL 6

Assisted Solution

by:Mahesh Bhutkar
Mahesh Bhutkar earned 167 total points
ID: 39814609
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
 

Author Comment

by:dkim18
ID: 39814750
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
 
LVL 6

Expert Comment

by:Mahesh Bhutkar
ID: 39814869
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
 
LVL 27

Expert Comment

by:mrcoffee365
ID: 39817637
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
 
LVL 35

Accepted Solution

by:
mccarl earned 167 total points
ID: 39820507
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

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
This video teaches viewers about errors in exception handling.

820 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question