Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

JAX-RS and JSON-P Integration

DZone's Guide to

JAX-RS and JSON-P Integration

This short post talks about support for JSON-P in JAX-RS 2.0.

· Java Zone
Free Resource

Bitbucket is for the code that takes us to Mars, decodes the human genome, or drives your next car. What will your code do? Get started with Bitbucket today, it's free.

The JSON Processing API (JSON-P) was introduced in Java EE 7. It provides a standard API to work with JSON data and is quite similar to its XML counterpart – JAXP. JSON-B (JSON Binding) API is in the works for Java EE 8.

Support for JSON-P in JAX-RS 2.0

JAX-RS 2.0 (also a part of Java EE 7) has out-of-the-box support for JSON-P artifacts like JsonObject, JsonArray and JsonStructure i.e. every JAX-RS 2.0 compliant implementation will provide built in Entity Providers for these objects, making it seamless and easy to exchange JSON data in JAX-RS applications

Some Examples

Sending JSON array from your JAX-RS resource methods

@GET
public JsonArray buildJsonArray(){
  return Json.createArrayBuilder().add("jsonp").add("jaxrs").build();
}

Here is another example of how you can accept a JSON payload from the client.

@POST
public void acceptJsonObject(JsonObject payload){
  System.out.println("the payload -- "+ payload.toString());
}

These are pretty simple examples, but I hope you get the idea….

Few Things to be Noted

  • No need to write custom MessageBodyReader or MessageBodyWriter implementations. As mentioned previously, the JAX-RS implementation does it for you for free!
  • This feature is not the same as being able to use JAXB annotations on POJOs and exchange JSON versions of the payload (by specifying the application/xml media type). This is not a standard feature yet, although I have experimented with this and observed that GlassFish 4.1 (Jersey) and Wildfly 8.x (RESTEasy) support this by default

Further Reading

Cheers!

Are you using Bitbucket to accomplish your company's mission? Share your company’s mission with #Forthecode for a chance to be featured on our homepage, our social media channels, or win a free t-shirt!

Topics:
java ,json ,jason-p ,jax-rs

Published at DZone with permission of Abhishek Gupta, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}