Previous Lecture Lecture 32 Next Lecture

Lecture 32, Tue 03/03

What is JSON?

JSON is used in a few places in the course, and widely throughout real-world software development.

Let’s talk a little about what JSON is, and how its used.

JSON in a Nutshell

This page explains the six types quite nicely: https://restfulapi.net/json-data-types/

A few tips

Where JSON is used in CS56 this quarter

JSON in Java

Note that the following is general Java, NOT Spring Boot specific.

There are a variety of libraries for dealing with JSON in Java.

The library we are using is called Jackson. In the pom.xml you’ll find:

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.10.0</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.10.0</version>
        </dependency>

With these two libraries, we can write so-called serializer/deserializer code for JSON.

More generally: Serializer/deserializer code converts between:

Examples from our code bases:

From UCSB Courses Search: https://github.com/ucsb-cs56-w20/ucsb-courses-search/blob/8cb242874d34aec4e3f2bf62baf220b464655221/src/main/java/edu/ucsb/cs56/ucsbapi/academics/curriculums/v1/classes/CoursePage.java#L39

From lab07:

/**
     * Create a FeatureCollection object from json representation
     * 
     * @param json String of json returned by API endpoint {@code /classes/search}
     * @return a new FeatureCollection object
     * @see <a href=
     *      "https://tools.ietf.org/html/rfc7946">https://tools.ietf.org/html/rfc7946</a>
     */
    public static FeatureCollection fromJSON(String json) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

            FeatureCollection featureCollection = objectMapper.readValue(json, FeatureCollection.class);
            return featureCollection;
        } catch (JsonProcessingException jpe) {
            logger.error("JsonProcessingException:" + jpe);
            return null;
        } catch (Exception e) {
            logger.error("Exception:" + e);
            return null;
        }
    }