Chapter 19. Processing JSON Data

Introduction

JSON, or JavaScript Object Notation, is:

  • A simple, lightweight data interchange format.
  • A simpler, lighter alternative to XML (see Chapter 20).
  • Easy to generate with printlns or with one of several APIs.
  • Recognized directly by the JavaScript parser in all web browsers.
  • Supported with add-on frameworks for all common languages (Java, C/C++, Perl, Ruby, Python, Lua, Erlang, Haskell, to name a few); a ridiculously long list of supported languages (including two dozen parsers for Java alone) is right on the homepage.

A simple JSON message might look like this:

softwareinfo.json

{
  "name": "robinparse",
  "version": "1.2.3",
  "description": "Another Parser for JSON",
  "className": "RobinParse",
  "contributors": [
        "Robin Smythe",
        "Jon Jenz",
        "Jan Ardann"
    ]
}

As you can see, the syntax is simple, nestable, and amenable to human inspection.

The JSON home page provides a concise summary of JSON syntax. There are two kinds of structure: JSON Objects (maps) and JSON Arrays (lists). JSON Objects are sets of name and value pairs, which can be represented either as a java.util.Map or as the properties of a Java object. For example, the fields of a LocalDate (see Finding Today’s Date) object for April 1, 2014, might be represented as:

{
        "year": 2014,
        "month": 4,
        "day" : 1
}

JSON Arrays are ordered lists, represented in Java either as arrays or as java.util.Lists. A list of two dates might look like this:

{
        [{
                "year": 2014,
                "month": 4,
                "day" : 1
        },{
                "year":

Get Java Cookbook, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.