JSON-LD is a JSON-based RDF format for representing Linked Data. It enables extending existing JSON objects with hypermedia capabilities; in other words, the capability to contain links in a machine-readable way.
In this tutorial, we’ll look at a couple of Jackson-based options to serialize and deserialize the JSON-LD format directly into POJOs. We’ll also cover the basic concepts of JSON-LD that will enable us to understand the examples.
The first time we see a JSON-LD document, we notice that some member names start with the @ character. These are JSON-LD keywords, and their values help us to understand the rest of the document.
To navigate the world of JSON-LD and to understand this tutorial, we need to be aware of four keywords:
Before we continue, we should take a look at our previous tutorials to refresh our memory on the Jackson ObjectMapper, Jackson Annotations, and custom Jackson Serializers.
Being already familiar with Jackson, we might realize that we could easily serialize two custom fields in any POJO as @id and @type using the @JsonProperty annotation. However, writing the @context by hand could be a lot of work and also prone to error.
Therefore, to avoid this error-prone approach, let’s take a closer look at two libraries that we could use for @context generation. Unfortunately, neither one of them is capable of generating all features of JSON-LD, but we’ll take a look at their shortcomings later as well.
Jackson-Jsonld** is a Jackson module that enables the annotation of POJOs in a convenient way to generate JSON-LD documents.**
First, let’s add jackson-jsonld as a dependency to the pom.xml:
<dependency> <groupId>com.io-informatics.oss</groupId> <artifactId>jackson-jsonld</artifactId> <version>0.1.1</version></dependency>
Then, let’s create our example POJO and annotate it for @context generation:
@JsonldResource@JsonldNamespace(name = "s", uri = "http://schema.org/")@JsonldType("s:Person")@JsonldLink(rel = "s:knows", name = "knows", href = "http://example.com/person/2345")public class Person { @JsonldId private String id; @JsonldProperty("s:name") private String name; // constructor, getters, setters}
Let’s deconstruct the steps to understand what we’ve done:
Next, let’s generate the JSON-LD document.
#data #jackson #json #data analysis