Solved

xml to json using JAXB AND JAXRS?

Posted on 2014-01-24
11
362 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 26

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
 
LVL 26

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
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 26

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 26

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

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…

760 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now