Technology news and views
RSS icon Email icon Home icon
  • Apache WINK: Issue with Single-Element JSON Array

    Posted on January 14th, 2011 Sandeep No comments

    For the last few weeks, I have been building a RESTful service using the very fine Apache WINK library. When the service is called, the server sends a response in JSON. One of the response elements was an array; in the resulting response, if the array contained a single element I noticed a strange thing:

    {
      "success": true,
      "subject": "Some subject",
      "origin": {
        "email": "some@email.example.com",
        "fullname": "Full name"
      },
      "listresult": {
        "r1": "yes",
        "r2": "no",
        "r3": "cancel"
      }
    }

    The expected response, of course, was for listresult to be as follows:

    "listresult": [
        {
        "r1": "yes",
        "r2": "no",
        "r3": "cancel"
        }
      ]

    The response class used JAXB annotations to set the element names and all the other good stuff. But for some reason, a single element list resulted in an erroneous response. Now, out-of-the-box, WINK comes configured with JSON4J as the  provider for JSON serialization. This library has an unfortunate side effect where the array serialization shows unexpected behavior: for a single element array, it was simply collapsing the array!

    Which led me to this posting on the WINK user forum. The solution was to use an alternative provider. As mentioned in that post, I decided to go ahead with Jackson, available here. I chose the easier route of simply replacing the JSON4J library with Jackson, both in my build environment and in the WEB-INF/lib folder.

    This approach worked out fine for my needs. If, however, you have multiple services hosted by the same application and want each of them to have a separate provider, I refer you to this excellent post on IBM developerWorks.