Home > Articles > Web Development

  • Print
  • + Share This
This chapter is from the book

JSON Serialization

Although RESTful services that produce XML are common, it is perhaps even more common for the service to produce JSON, or the JavaScript Object Notation. JSON is a simple notation based on name/value pairs and ordered lists that are both easy to produce in many languages and extremely easy (in fact, part of the language) for JavaScript to parse and create. It’s actually nothing more than a proper subset of the JavaScript object literal notation.3

When it comes to Java, especially inside the WebSphere Liberty Profile, you have several ways to produce JSON, just as you have different ways of producing XML. You can, of course, manually hand-code it, although that is not recommended. For more complex situations requiring a great deal of flexibility, a dynamic method of producing JSON might be needed, just as a dynamic approach to producing XML is sometimes helpful. However, the most common approach for producing JSON is the same as that for XML—using static annotations with JAXB.

A Simple Transaction Example with JAX-RS

To show how annotations for JSON work, we going to introduce another service from the list earlier in the chapter. The Transaction service enables you to view a transaction with GET, view a list of transactions with GET, and also create a new transaction by POSTing to the appropriate URL.

Let’s start by introducing our BankingTransaction class (see Listing 4.7).

Listing 4.7 BankingTransaction Class

package com.ibm.mwdbook.restexamples;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class BankingTransaction {
      @XmlElement
      protected String id;
      @XmlElement
      protected Date;
      @XmlElement
      protected double amount;
      @XmlElement
      protected String currency;
      @XmlElement
      protected String merchant;
      @XmlElement(name="memo")
      protected String description;
      @XmlElement

      protected String tranType;

      public BankingTransaction() {
      }

      public BankingTransaction(String id, long date,String currency, String memo, double amount, String tranType, String merchant) {
            setId(id);
            setDescription(memo);
            setAmount(amount);
            setCurrency(currency);
            setTranType(tranType);
            setMerchant(merchant);
            setDate(new Date(date));
      }
      public String getDescription() {
            return description;
      }
      public void setDescription(String aDescription) {
            description = aDescription;
      }
      public double getAmount() {
            return amount;
      }
      public void setAmount(double anAmount) {
            amount = anAmount;
      }
      public String getCurrency() {
            return currency;
      }
      public void setCurrency(String currency) {
            this.currency = currency;
      }
      public String getId() {
            return id;
      }
      public void setId(String id) {
            this.id = id;
      }
      public String getTranType() {
            return tranType;
      }
      public void setTranType(String tranType) {
            this.tranType = tranType;
      }
      public String getMerchant() {
            return merchant;
      }
      public void setMerchant(String merchant) {
            this.merchant = merchant;
      }
      public Date getDate() {
            return date;
      }
      public void setDate(Date date) {
            this.date = date;
      }
}

At this point, you might be thinking that this looks exactly like the annotations in the previous example. That’s the point. If you use JAXB annotations, you have to annotate the class only once; you don’t have to put in separate annotations for JSON and XML. Also, it’s not entirely the same. Note that, in this case, we annotated the fields and not the properties—in practice, there is little difference between the two, and you can use either.

Handling Entity Parameters with POST and the Consumes Annotation

Now that you’ve seen how you can create a class with annotations that work for both XML and JSON, you can explore how to add methods to a service to take advantage of that. We’re only introducing a couple new concepts in this part of the example—take a look at the following new method from the AccountResource class:

@Path("{account}/transaction")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@POST
public int putTransaction(@PathParam(value="account") int account,
                          BankingTransaction aTrans){
    return txnDao.putTransaction(account, aTrans);
}

The first new annotation is the @Consumes annotation. None of the previous services we’ve written have taken in any message bodies, so this is the first time we’ve needed to use it. As you can see, it’s essentially similar to the @Produces annotation. The interesting part is how the browser interacts with the server based on these annotations. In this case, we’re being very restrictive—we insist that the format of the message body be in JSON, but we also provide the response back in JSON. This information about what format is acceptable to the server and the client is communicated in specific HTTP headers. Figure 4.11 shows the interaction.

Figure 4.11

Figure 4.11 Header and annotation interaction

For a resource method to process a request, the Content-Type header of the request must be compatible with the supported type of the @Consumes annotation (if one is provided). Likewise, the Accept header of the request must be compatible with the supported type of the @Produces annotation. The Content-type header of the response will be set to a type listed in the @Produces annotation. This case is very simple—we’re allowing only a single content type (application/json) into our service and a single content type (also application/json) out of the service; more complex cases might require content negotiation, which we discuss in more detail in the later section “More on Content Negotiation.”

Looking back at the code for our BankingTransaction class, you see one more interesting fact about the putTransaction() method. Not only does it take a @PathParam, as have several of our preceding examples, but another method parameter is not attached to a @PathParam annotation: an instance of a BankingTransaction named aTrans. Where does this parameter come from? The JAX-RS specification is very clear on this: A resource method may have only one nonannotated parameter; that special parameter is called the entity parameter and is mapped from the request body. It is possible to handle that mapping yourself, but in our case (and in most cases), that mapping will be handled by a mapping framework such as JAXB.

The Use of Singletons in Application Classes

Before you can test your simple transaction-posting method, you need to understand a couple more concepts. The first is how we’re implementing the DAO for this example. All the previous DAOs we implemented were just for prepopulating a collection with examples that we could retrieve with a GET. However, if we are now enabling POST, we want to be able to check that the information that we POST to the resource will be available on the next GET to that resource. In a “real” implementation of a DAO, that would be fine—we’d just fetch the values from a relational database on a GET and create the new rows on a POST. However, in our simplified example, we don’t yet have that option (we show that in Chapter 6). Our solution for this case is very simple—we add a static variable that is an instance of our DAO to the DAO class. That way, we implement what in Design Patterns parlance is often called a singleton, a class that has a single instance. You can see this in the source code (see Listing 4.8) of our very simple BankingTransactionDao, which holds on to a single static variable that is an instance of the class that we name instance.

Listing 4.8 BankingTransactionDao Class

package com.ibm.mwdbook.restexamples;

import java.util.HashMap;

public class BankingTransactionDao {

      static BankingTransactionDao instance = new BankingTransactionDao();

      public static BankingTransactionDao getInstance() {
            return instance;
      }

      HashMap<String, BankingTransaction> accounts =
              new HashMap<String, BankingTransaction>();
      int lastId=123;

      public BankingTransactionDao() {
            String key=deriveKey(123,123);
            BankingTransaction aTrans = new BankingTransaction("123", 1388249396976L,"USD", "paycheck", 110.0, "DEPOSIT", "DIRECT");
            accounts.put(key, aTrans);
      }
      private String deriveKey(int account, int id) {
            StringBuffer buf = new StringBuffer();
            buf.append(account);
            buf.append("-");
            buf.append(id);
            String key = buf.toString();
            return key;
      }

      public BankingTransaction getTransaction(int account, int id){
            String key = deriveKey(account, id);
            return (BankingTransaction)accounts.get(key);
      }

      public int putTransaction(int account, BankingTransaction aTrans)
      {
            int id=getNextID();
            String key = deriveKey(account,id);
            aTrans.setId(Integer.toString(id));
            accounts.put(key, aTrans);
            return id;
      }

      private int getNextID() {
            return ++lastId;
      }
}

Now the variable declaration of txnDao within our AccountResource class simply needs to obtain the instance of the Dao by invoking the getInstance() method, as follows:

BankingTransactionDao txnDao = BankingTransactionDao.getInstance();

However, although this is simple, it’s not the best solution for most cases. A better approach is to consider that JAX-RS provides you with the capability to produce singleton instances of resource classes. In JAX-RS, the normal process is that a new instance of the resource class is created for every request. However, this might not always be the best choice. Even though it is a best practice that resources be stateless (as are the REST services themselves), sometimes a singleton instance can be useful—notably, when it needs to contain cached information to improve performance. Our simple service has another reason for this—to provide a stateful test service that mimics a service implemented on a backing store such as a relational database. You achieve this through the use of the @Singleton annotation. When your resource class contains this annotation, the resource class itself is considered to be a singleton and will live through the lifetime of the server. We show you many examples of @Singleton-annotated resource classes in our more fully fleshed-out example in Chapter 7.

To complete this example, simply create a new class for your BankingTransactionDao and enter the previous code and then modify the AccountResource class to add the variable declaration for the txnDao and the new putTransaction() method we earlier described. You then need to let Eclipse patch up your import list using Source > Organize Imports so that the example compiles cleanly.

Testing POST and Other Actions with RESTClient

Now it’s time to test adding a banking transaction to our newly defined POST resource method in our AccountResource class. However, that brings up a problem: In all the previous examples, we’ve been testing only GETting a response from a resource, which can be tested in any browser. How can we test POSTing to a resource? That requires you to provide a message body and also (as you’ve already seen) a special Content-Type HTTP header. Essentially, a basic browser won’t do for this case. You can look into several testing options:

  • Curl (http://curl.haxx.se/) is a commonly used command-line client tool for transferring data with a URL syntax that can be used over a variety of protocols, including HTTP. Curl is especially useful for scripting if you need to write reusable test scripts.
  • rest-client (http://code.google.com/p/rest-client/) is a simple Java GUI application from Google (although it also comes in a command-line version) that can be used for testing REST resources.

The solution we demonstrate in this chapter fits better with our methodology of testing resource methods within the browser: We use RESTClient, a free Mozilla add-on written by Chao Zhou that is available on the Mozilla add-ons site (see https://addons.mozilla.org/en-US/firefox/addon/restclient/). Chapter 9 discusses similar plug-ins for Chrome.

Obtaining RESTClient and installing it into Firefox is easy; just visit the site and follow the instructions. To start a RESTClient session, click the red RESTClient icon in the upper-right corner of your screen that is added during the installation process. You will see a new tab that looks something like the one in Figure 4.12.

Figure 4.12

Figure 4.12 RESTClient for POST testing

When you are ready to test your new service, first select POST from the Method drop-down list. Then type the following URL on the URL line:

http://localhost:9080/RestServicesSamples/banking/accounts/123/
transaction

You need to add an appropriate Content-Type header. Click the Headers menu and choose Custom Header; then in the Request Header dialog box, type Content-Type as the Name and application/json as the value before clicking OK to dismiss the dialog box. Finally, type this into the body text area and click Send:

{"currency":"USD","memo":"books","amount":10,"tranType":"PURCHASE",
"merchant":"Amazon" }

If you look at either of the Response Body tabs, they should show the new ID number of your transaction (124 if you’ve added only one BankingTransaction). Likewise, the Response Header tab should show a status code of 200 OK and a Content-Type of application/json, as explained in our earlier diagram.

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020