?
Solved

xml to json using JAXB AND JAXRS?

Posted on 2014-01-24
11
Medium Priority
?
374 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Learn by Doing. Anytime. Anywhere.

Do you like to learn by doing?
Our labs and exercises give you the chance to do just that: Learn by performing actions on real environments.

Hands-on, scenario-based labs give you experience on real environments provided by us so you don't have to worry about breaking anything.

 
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 664 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 668 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 36

Accepted Solution

by:
mccarl earned 668 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: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

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.

Question has a verified solution.

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

Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Suggested Courses

762 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