Solved

xml to json using JAXB AND JAXRS?

Posted on 2014-01-24
11
366 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
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 
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

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

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

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

770 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