DZone
Integration Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Integration Zone > Marshalling Java to JSON in JAX-RS

Marshalling Java to JSON in JAX-RS

Thamizh Arasu user avatar by
Thamizh Arasu
·
Jan. 02, 15 · Integration Zone · Interview
Like (2)
Save
Tweet
27.84K Views

Join the DZone community and get the full member experience.

Join For Free

In this article, I am going to explain about the purpose and the process of writing custom marshaller for web services. First we have to be clear on what is marshaller. Marshalling is the nothing but the process of converting in-memory object into persisting or transportable format.

Now a days most of the web services are returning the response as JSON object. Some people are still using XML as their preferred transport medium.

JAX-RS api has introduced a generic and pluggable interface called MessageBodyWriter for doing the marshalling.

Use-case:

We will take an use-case in-order to understand the situation little better. We have a Java bean called Book. Now we have to write a REST service which will fetch the Java object from the given ID and return JSON response back to the client.

Book.java:

public class Book {
	private String title;
	private String author;

	public Book(String title, String author) {
	 this.title = title;
	 this.author = author;
	}

	public String getTitle() {
	 return title;
	}

	public String getAuthor() {
	 return author;
	}
}

BookResource.java:

public class BookResource {

	 @GET
	 @Path("{id}")
	 @Produces(MediaType.APPLICATION_JSON)
	 public Book getBook(@PathParam("id") String id) {

	 //DataProvider is simple data holder
	 DataProvider dataProvider = DataProvider.getInstance();
	 return dataProvider.getBook(id);
	}
}

In the above REST method, we have just returned Java object itself to the client as response. If you notice the @Produces, we are returning the JSON contents back to the client.



Stumbled! The magic happens at the marshalling layer. Now we will see how the marshalling code will look like.

BookJsonMarshaller.java:

@Provider
@Produces(MediaType.APPLICATION_JSON)
public class BookJsonMarshaller implements MessageBodyWriter<Book> {

	 @Override
	 public long getSize(Book book, Class<?> clazz, Type type, Annotation[] annotations, MediaType mediaType) {
	 return -1;
	}

	 @Override
	 public boolean isWriteable(Class<?> clazz, Type type, Annotation[] annotations, MediaType mediaType) {
	 return clazz == Book.class;
	}

	 @Override
	 public void writeTo(Book book, Class<?> clazz, Type type, Annotation[] annotations, MediaType mediaType,
	 MultivaluedMap<String, Object> valueMap, OutputStream stream) throws IOException, WebApplicationException {

	 JsonObject jsonObject = Json.createObjectBuilder()
	  .add("title", book.getTitle())
	  .add("author", book.getAuthor()).build();

	 DataOutputStream outputStream = new DataOutputStream(stream);
	 outputStream.writeBytes(jsonObject.toString());
	}
}

We have to look 'writeTo' method just to understand the process. The first arguments is coming from the injection layer so the current Java object will be available to this processor. Now we have process the Java object and should generate JSON object. In this example I have used the 'javax.json.jar' for generating the JSON content. Finally the JSON content should be written into output stream.

Finally we have register the provider (BookJsonMarshaller) into our application like other resources...

Before we conclude this article, you may have one question. Why we need to write the custom marshaller for processing the Java object. Is it not possible by default? You question is valid. This is still possible. But if you want to have a full control over the generated JSON content, we have to write our own @Providers...

I hope you have enjoyed reading this article. If you have any questions or comments please reply to this thread... We will meet again with another discussion.

For code reference, don't forget to visit Github

Advance Christmas wishes to my readers!

JSON Java (programming language) Marshalling (computer science) Object (computer science)

Published at DZone with permission of Thamizh Arasu, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • When Microservices Are a Bad Idea
  • Trending Programming Language to Learn
  • What to Know About Python and Why Its the Most Popular Today
  • Java Class Loading: Performance Impact

Comments

Integration Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo