Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/jsonx-org/java

Reference implementation of the JSONx specification for the Java platform, including encoding, decoding, processing, validation, and binding.
https://github.com/jsonx-org/java

binding binding-generator consumer-driven-contracts enterprise generator java jsd jsdx json json-schema jsonx jsonx-schema schema validator

Last synced: 22 days ago
JSON representation

Reference implementation of the JSONx specification for the Java platform, including encoding, decoding, processing, validation, and binding.

Awesome Lists containing this project

README

        

# JSONx Framework for Java

> **JSON Schema for the enterprise**

[![Build Status](https://github.com/jsonx-org/java/actions/workflows/build.yml/badge.svg)](https://github.com/jsonx-org/java/actions/workflows/build.yml)
[![Coverage Status](https://coveralls.io/repos/github/jsonx-org/java/badge.svg)](https://coveralls.io/github/jsonx-org/java)
[![Javadocs](https://www.javadoc.io/badge/org.jsonx/jsonx.svg)](https://www.javadoc.io/doc/org.jsonx/jsonx)
[![Released Version](https://img.shields.io/maven-central/v/org.jsonx/jsonx.svg)](https://mvnrepository.com/artifact/org.jsonx/jsonx)
![Snapshot Version](https://img.shields.io/nexus/s/org.jsonx/jsonx?label=maven-snapshot&server=https%3A%2F%2Foss.sonatype.org)

| **Submodule** | **Summary** |
|:-|:-|
| [runtime][runtime] | API to bind Java classes to JSON objects whose structure is expressed in the
[JSON Schema Definition Language][schema]. |
| [generator][generator] | Utility to generate Java binding classes from a JSD(x) schema. |
| [validator][validator] | Utility to validate JSON documents against a JSD(x) schema. |
| [jsonx-maven-plugin][jsonx-maven-plugin] | Maven plugin to generate and convert JSONx and JSD(x) bindings. |
| [jaxrs][jaxrs] | JAX-RS `@Provider` to read and write JSON documents with the [JSONx Runtime API][#runtime]. |
| [jsonxml][jsonxml] | Utility to convert and validate JSON and JSONx documents. |
| [sample][sample] | Sample applications. |

## Abstract

The JSONx Framework for Java provides a reference implementation processor, validator, and runtime API for the [JSON Schema Definition Language (JSD)][schema], which is a schema language for JSON designed in close resemblance to the [XMLSchema][xmlschema] specification. The framework also provides a collection of structural and functional patterns intended to help developers work with JSON documents.

This document introduces the JSONx Framework for Java, and presents a directory of links to its constituent parts and related resources.

## Table of Contents

  1 [Introduction](#1-introduction)

    1.1 [Conventions Used in This Document](#11-conventions-used-in-this-document)

  2 [Use-Cases](#2-use-cases)

    2.1 [Consumer Driven Contracts](#21-consumer-driven-contracts)

  3 [JSON Schema Definition Language][#jsd]

    3.1 [Purpose](#31-purpose)

    3.2 [Requirements](#32-requirements)

    3.3 [Getting Started](#33-getting-started)

    3.4 [JSD vs JSDx](#34-jsd-vs-jsdx)

    3.5 [Specification](#35-specification)

  4 [JSONx Runtime API][#runtime]

    4.1 [Purpose](#41-purpose)

    4.2 [Requirements](#42-requirements)

    4.3 [Getting Started][#invoice-example]

    4.4 [Specification](#44-specification)

  5 [JSONx Binding Generator](#5-jsonx-binding-generator)

    5.1 [Purpose](#51-purpose)

    5.2 [Requirements](#52-requirements)

    5.3 [Getting Started](#53-getting-started)

       5.3.1 [Generator](#531-generator)

       5.3.2 [Converter][#converter]

    5.4 [Specification](#54-specification)

  6 [JSONx Validator](#6-jsonx-validator)

    6.1 [Purpose](#61-purpose)

    6.2 [Requirements](#62-requirements)

    6.3 [Getting Started](#63-getting-started)

       6.3.1 [Valid Case](#631-valid-case)

       6.3.2 [Invalid Case](#632-invalid-case)

    6.4 [Specification](#64-specification)

  7 [JSONx Integration for JAX-RS](#7-jsonx-integration-for-jax-rs)

    7.1 [Purpose](#71-purpose)

    7.2 [Requirements](#72-requirements)

    7.3 [Getting Started](#73-getting-started)

    7.4 [Specification](#74-specification)

  8 [JSONx Maven Plugin](#8-jsonx-maven-plugin)

    8.1 [Purpose](#81-purpose)

    8.2 [Requirements](#82-requirements)

    8.3 [Getting Started](#83-getting-started)

    8.4 [Specification](#84-specification)

  9 [JsonXml](#9-jsonxml)

    9.1 [Purpose](#91-purpose)

    9.2 [Requirements](#92-requirements)

    9.3 [Getting Started](#93-getting-started)

       9.3.1 [JSON-to-XML](#931-json-to-xml)

       9.3.2 [XML-to-JSON](#932-xml-to-json)

    9.4 [Specification](#94-specification)

  10 [Contributing](#10-contributing)

  11 [Special Thanks](#11-special-thanks)

  12 [License](#12-license)

## 1 Introduction

The JSONx Framework for Java was created to help developers address common problems and use-cases when working with JSON documents. The JSONx Framework for Java offers structural and functional patterns that systematically reduce errors and pain-points commonly encountered when developing software that interfaces with JSON. The structural patterns are defined in the [JSON Schema Definition Language][schema], which is a programming-language-agnostic schema language used to describe constraints and document the meaning, usage and relationships of the constituent parts of JSON documents. The functional patterns are reference implementations of the specification of the schema language, providing utilities that address common use-cases for applications that use JSON in one way or another. Common use-cases include:

1. Definition of a normative contract between a producer and consumer of JSON documents.
1. Validation of JSON documents conforming to a respective schema document.
1. Java class runtime API for JSON documents conforming to a respective schema document.

### 1.1 Conventions Used in This Document

The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [RFC2119](https://www.ietf.org/rfc/rfc2119.txt).

## 2 Use-Cases

The following sections lists common use-cases where JSONx Framework for Java can be used.

### 2.1 Consumer Driven Contracts

The JSONx Framework for Java was created specifically with [Consumer Driven Contracts][cdc] in mind. With the [JSON Schema Definition Language (JSD)][#jsd], one can create a Consumer Driven Contract (CDC) with a model that includes the capacity to evolve based on schema versioning. Additionally, the JSD can be used by producers and consumers to validate documents in a communication protocol.

The following example illustrates a simple protocol that uses the CDC approach, and consists of the actors:

1. **Producer**: Representing the provider of the ProductSearch service.
1. **Consumer1**: The first consumer of the ProductSearch service.
1. **Consumer2**: The second consumer of the ProductSearch service.

Consider a simple ProductSearch service, which allows consumer applications to search a product catalogue.

Version **v1** of the protocol defines the contract:

* **Request**

```
GET /ProductSearch?name=
```

* **Response**

```diff
{
"Version": "v1",
"CatalogueID": ,
"Name": ,
"Price": ,
"Manufacturer": ,
"InStock":
}
```

The schema that describes the **Response** contract is:

###### **JSD**

```json
{
"jx:ns": "http://www.jsonx.org/schema-0.4.jsd",
"jx:schemaLocation": "http://www.jsonx.org/schema-0.4.jsd http://www.jsonx.org/schema.jsd",

"product": { "jx:type": "object", "abstract": true, "properties": {
"CatalogueID": { "jx:type": "number", "range": "[1,]", "scale": 0, "nullable": false},
"Name": { "jx:type": "string", "pattern": "\\S|\\S.*\\S", "nullable": false },
"Price": { "jx:type": "string", "pattern": "\\$\\d+\\.\\d{2}", "nullable": false },
"Manufacturer": { "jx:type": "string", "pattern": "\\S|\\S.*\\S", "nullable": false },
"InStock": { "jx:type": "boolean", "nullable": false} } },

"product1": { "jx:type": "object", "extends": "product", "properties": {
"Version": { "jx:type": "string", "pattern": "v1", "nullable": false } } }
}
```

###### **JSDx**

```xml









```

_**Note:** The [Converter][#converter] utility automatically converts between JSD and JSDx._

All actors -- **Producer**, **Consumer1**, and **Consumer2** -- agree on the contract, and implement and integrate the protocol into their systems. To assert receipt of contract-compliant documents, all actors use the contract definition to automatically validate received and sent messages.

After many months of running in production, **Consumer2** issues a request to the **Producer** to provide additional information in the response. Specifically, **Consumer2** requests for the addition of another field in the JSON response:

```diff
{
- "Version": "v1.0",
+ "Version": "v2.0",
"CatalogueID": ,
"Name": ,
"Price": ,
"Manufacturer": ,
"InStock": ,
+ "Description":
}
```

To satisfy **Consumer2**'s request, the contract is updated to support version **v2** of the **Response**:

###### **JSD**

```diff
{
"jx:ns": "http://www.jsonx.org/schema-0.4.jsd",
"jx:schemaLocation": "http://www.jsonx.org/schema-0.4.jsd http://www.jsonx.org/schema.jsd",

"product": { "jx:type": "object", "abstract": true, "properties": {
"CatalogueID": { "jx:type": "number", "range": "[1,]", "scale": 0, "nullable": false},
"Name": { "jx:type": "string", "pattern": "\\S|\\S.*\\S", "nullable": false },
"Price": { "jx:type": "string", "pattern": "\\$\\d+\\.\\d{2}", "nullable": false },
"Manufacturer": { "jx:type": "string", "pattern": "\\S|\\S.*\\S", "nullable": false },
"InStock": { "jx:type": "boolean", "nullable": false} } },

"product1": { "jx:type": "object", "extends": "product", "properties": {
"Version": { "jx:type": "string", "pattern": "v1", "nullable": false } } }

+ "product2": { "jx:type": "object", "extends": "product", "properties": {
+ "Version": { "jx:type": "string", "pattern": "v2", "nullable": false },
+ "Description": { "jx:type": "string", "pattern": "\\S|\\S.*\\S", "nullable": false } } }
}
```

###### **JSDx**

```diff









+
+
+
+

```

_**Note:** The [Converter][#converter] utility automatically converts between JSD and JSDx._

With this approach, the **v2** evolution of the contract satisfies **Customer2**. And, since the contract also retains support for **v1**, integration with **Customer1** is unaffected.

_For the application code, see **[Sample: Consumer Driven Contracts][sample-cdc]**._

## 3 JSON Schema Definition Language

Describes JSON documents using schema components to constrain and document the meaning, usage and relationships of their constituent parts: value types and their content.

### 3.1 Purpose

Provide a schema language to describe normative contracts between producer and consumer ends of a protocol exchanging JSON documents.

### 3.2 Requirements

1. The schema language MUST constrain and document the meaning, usage, constraints and relationships of the constituent parts of a JSON document.

1. The schema language MUST provide meaningful and useful constraint rules for the 5 JSON value types:

`boolean`, `number`, `string`, `object`, `array`.

1. The schema language MUST support schema descriptions for any and all legal JSON documents, as specified by [RFC2119](https://www.ietf.org/rfc/rfc2119.txt).

1. The schema language MUST be free-of and agnostic-to patterns specific to any particular programming language.

1. The schema language MUST be able to describe itself.

### 3.3 Getting Started

The JSON Schema Definition Language can be expressed in 2 forms: JSD (Json Schema Document), and JSDx (JSD in XML semantics).

Create `schema.jsd` or `schema.jsdx` with the following content:

###### **JSD**

```json
{
"jx:ns": "http://www.jsonx.org/schema-0.4.jsd",
"jx:schemaLocation": "http://www.jsonx.org/schema-0.4.jsd http://www.jsonx.org/schema.jsd",

"myNumber": { "jx:type": "number", "range": "[-1,1)" },
"myString": { "jx:type": "string", "pattern": "[a-z]+" },
"myObject": {
"jx:type": "object", "properties": {
"myArray": {
"jx:type": "array", "elements": [
{ "jx:type": "boolean" },
{ "jx:type": "reference", "type": "myNumber" },
{ "jx:type": "reference", "type": "myString" },
{ "jx:type": "array", "elements": [
{ "jx:type": "boolean" },
{ "jx:type": "number", "range": "[0,100]", "scale": 0 },
{ "jx:type": "string", "pattern": "[0-9]+" },
{ "jx:type": "any", "types": "myNumber myString" } ]},
{ "jx:type": "reference", "type": "myObject" },
{ "jx:type": "any", "types": "myString myObject" }]
}
}
}
}
```

###### **JSDx**

```xml

















```

_**Note:** You can use the [Converter][#converter] utility to automatically convert between JSD and JSDx._

This example defines a schema with 3 types that express the following structure:

1. Type **`myNumber`**: A `number` between the range -1 (inclusive) and 1 (exclusive).
1. Type **`myString`**: A `string` with the regex patter "[a-z]+".
1. Type **`myObject`**: An `object` that has one property:
1. "myArray": An `array` that defines a sequence of elements:
1. `boolean`
1. **`myNumber`**
1. **`myString`**
1. An `array` with the following elements:
1. `boolean`
1. An integer `number` between 0 and 100.
1. A `string` of pattern "[0-9]+"
1. Either **`myNumber`** or **`myString`**.
1. `myObject`
1. Either **`myString`** or **`myObject`**.

### 3.4 JSD vs JSDx

The JSDx format offers XML validation, and using an XML IDE like [oXygen XML Editor][oxygenxml] offers edit-time XML validation, such as:

When using the JSDx format with the [oXygen XML Editor][oxygenxml], the auto-completion features of the editor will guide you in writing the schema. With the JSDx format, the XML editor will also validate keys and keyrefs to ensure that declared types are referenced correctly.

### 3.5 Specification

_For a detailed specification of the schema language, see **[JSON Schema Definition Language][schema]**._

## 4 JSONx Runtime API

Provides a way for JSON objects whose structure is expressed in the [JSON Schema Definition Language][schema] to be validated, parsed and marshaled, to and from Java objects of strongly-typed classes.

### 4.1 Purpose

Provide a runtime API for parsing and marshaling JSON documents to and from strongly-typed Java classes.

### 4.2 Requirements

1. The runtime API MUST be able to model the full scope of normative meaning, usage, constraints and relationships of the constituent parts of a JSON document as specifiable with the schema language.

1. The runtime API MUST enforce (via validation) the full scope of normative meaning, usage, constraints and relationships of the constituent parts of a JSON document as specifiable in the schema language.

1. The runtime API MUST produce clear and useful error messages when exception of schema document constraints are encountered during validation of JSON documents.

1. The runtime API MUST constrain the constituent parts of a schema document to Java type bindings that are as lightweight as necessary to retain the full normative scope of specification of the schema language.

1. The runtime API MUST use light coupling, not imposing requirements for exclusionary patterns onto a class model of binding classes.

1. The runtime API MUST offer easy patterns for manual description of bindings.

1. The runtime API MUST be straightforward, intuitive, and resilient to human error.

### 4.3 Getting Started

The JSONx Runtime API uses annotations to bind class definitions to usage, constraints and relationships specifiable in the schema language.

The following illustrates usage of the runtime API with an example of an **invoice**.

  1. Create `invoice.jsd` or `invoice.jsdx` in `src/main/resources/`:

###### **JSD**

```json
{
"jx:ns": "http://www.jsonx.org/schema-0.4.jsd",
"jx:schemaLocation": "http://www.jsonx.org/schema-0.4.jsd http://www.jsonx.org/schema.jsd",

"money": { "jx:type": "number", "range": "[0,]", "scale": 2},
"positiveInteger": { "jx:type": "number", "range": "[1,]", "scale": 0},
"date": { "jx:type": "string", "pattern": "-?\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(02-(0[1-9]|1\\d|2\\d))|((0[469]|11)-(0[1-9]|[12]\\d|30)))" },
"nonEmptyString": { "jx:type": "string", "pattern": "\\S|\\S.*\\S" },
"address": { "jx:type": "object", "properties": {
"name": { "jx:type": "reference", "nullable": false, "type": "nonEmptyString" },
"address": { "jx:type": "reference", "nullable": false, "type": "nonEmptyString" },
"city": { "jx:type": "reference", "nullable": false, "type": "nonEmptyString" },
"postalCode": { "jx:type": "reference", "nullable": false, "type": "nonEmptyString", "use": "optional" },
"country": { "jx:type": "reference", "type": "nonEmptyString" } }
},
"invoice": { "jx:type": "object", "properties": {
"number": { "jx:type": "reference", "type": "positiveInteger" },
"date": { "jx:type": "reference", "type": "date" },
"billingAddress": { "jx:type": "reference", "type": "address" },
"shippingAddress": { "jx:type": "reference", "type": "address" },
"billedItems": { "jx:type": "array", "nullable": false, "elements": [
{ "jx:type": "reference", "type": "item" } ] } }
},
"item": { "jx:type": "object", "properties": {
"description": { "jx:type": "reference", "nullable": false, "type": "nonEmptyString" },
"code": { "jx:type": "reference", "nullable": false, "type": "positiveInteger" },
"quantity": { "jx:type": "reference", "nullable": false, "type": "positiveInteger" },
"price": { "jx:type": "reference", "nullable": false, "type": "money" } }
}
}
```

###### **JSDx**

```xml


























```

_**Note:** You can use the [Converter][#converter] utility to automatically convert between JSD and JSDx._

  2. With the `invoice.jsd` or `invoice.jsdx`, you can use the [`jsonx-maven-plugin`][jsonx-maven-plugin] to automatically generate the Java class files. In your POM, add:

```xml

org.jsonx
jsonx-maven-plugin
0.4.0



generate

generate-sources

${project.build.directory}/generated-sources/jsonx
com.example.invoice.

src/main/resources/invoice.jsd



```

  3. **(Alternatively)** Create the Java class files by hand:

_**Note:** Set-ters and get-ters have been replaced with public fields for conciseness._

```java
import org.jsonx.*;

public class Address implements JxObject {
@StringProperty(pattern="\\S|\\S.*\\S", nullable=false)
public String name;

@StringProperty(pattern="\\S|\\S.*\\S", nullable=false)
public String address;

@StringProperty(pattern="\\S|\\S.*\\S", nullable=false)
public String city;

@StringProperty(pattern="\\S|\\S.*\\S", use=Use.OPTIONAL, nullable=false)
public String postalCode;

@StringProperty(pattern="\\S|\\S.*\\S")
public String country;
}
```

```java
import org.jsonx.*;

public class Item implements JxObject {
@StringProperty(pattern="\\S|\\S.*\\S", nullable=false)
public String description;

@NumberProperty(range="[1,]", scale=0, nullable=false)
public long code;

@NumberProperty(range="[1,]", scale=0, nullable=false)
public long quantity;

@NumberProperty(range="[1,]", scale=2, nullable=false)
public java.math.BigDecimal price;
}
```

```java
import org.jsonx.*;

public class Invoice implements JxObject {
@NumberProperty(range="[1,]", scale=0)
public Long number;

@StringProperty(pattern="-?\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(02-(0[1-9]|1\\d|2\\d))|((0[469]|11)-(0[1-9]|[12]\\d|30)))")
public String date;

@ObjectProperty
public Address billingAddress;

@ObjectProperty
public Address shippingAddress;

@ObjectElement(id=0, type=Item.class)
@ArrayProperty(elementIds={0}, nullable=false)
public java.util.List billedItems;
}
```

  4. You can use these classes to represent `Address`es, `Item`s, and `Invoice`s.

```java
Address address = new Address();
address.name = "John Doe";
address.address = "111 Wall St.";
address.city = "New York";
address.postalCode = "10043";
address.country = "USA";

Item item = new Item();
item.code = 123;
item.description = "Pocket Protector";
item.price = new BigDecimal("14.99");
item.quantity = 5;

Invoice invoice = new Invoice();
invoice.number = 14738L;
invoice.date = "2019-05-13";
invoice.billingAddress = address;
invoice.shippingAddress = address;
invoice.billedItems = Collections.singletonList(item);
```

  5. You can now marshal the Java objects to JSON:

```java

String json = JxEncoder._2.marshal(invoice);
System.out.println(json);
```

... will produce:

```json
{
"number": 14738,
"date": "2019-05-13",
"billingAddress": {
"name": "John Doe",
"address": "111 Wall St.",
"city": "New York",
"postalCode": "10043",
"country": "USA"
},
"shippingAddress": {
"name": "John Doe",
"address": "111 Wall St.",
"city": "New York",
"postalCode": "10043",
"country": "USA"
},
"billedItems": [{
"description": "Pocket Protector",
"code": 123,
"quantity": 5,
"price": 14.99
}]
}
```

  6. You can also parse the JSON into Java objects:

```java
Invoice invoice2 = JxDecoder.parseObject(Invoice.class, new JsonReader(new StringReader(json)));
assertEquals(invoice, invoice2);
```

_For the application code, see **[Sample: Invoice][sample-invoice]**._

### 4.4 Specification

_For a detailed specification of the runtime API, see **[JSONx Runtime API][runtime]**._

## 5 JSONx Binding Generator

Consumes a JSD schema, and generates classes that use the [JSONx Runtime API][#runtime] to achieve binding between JSON documents conforming to a JSD schema, and Java object represetations of these documents.

### 5.1 Purpose

Provide a binding generator utility for automatic generation of binding classes from a schema document.

### 5.2 Requirements

1. The binding generator MUST be able to consume a schema document, and produce Java class definitions (`.java` files) that use the runtime API.

1. The binding generator MUST be able to consume Java class definitions (`.class` files) utilizing the runtime API, and produce a schema document.

1. The binding generator MUST create Java classes (`.java` files) that encode the full normative scope of the schema document.

1. The binding generator MUST represent the constituent parts of a schema document with Java type bindings that are as strongly-typed as possible, but not limiting in any way with regard to the definition of the respective constituent part.

1. The binding generator MUST be able to validate a schema document.

### 5.3 Getting Started

The JSONx Binding Generator provides convenience utilities for generating bindings and converting schema documents. The following illustrates example usage of the `Generator` and `Converter` executable classes.

#### 5.3.1 `Generator`

The following example generates binding classes (`.java` files) in `target/generated-sources/jsonx` for the schema document at `src/main/resources/example.jsd`, with prefix `org.example$`.

```bash
java -cp ... org.jsonx.Generator --prefix org.example$ -d target/generated-sources/jsonx src/main/resources/example.jsd
```

#### 5.3.2 `Converter`

The following example converts the JSD file at `src/main/resources/example.jsd` to a JSDx file in `target/generated-resources`.

```bash
java -cp ... org.jsonx.Converter src/main/resources/example.jsd target/generated-resources/example.jsdx
```

### 5.4 Specification

_For a detailed specification of the binding generator, see **[JSONx Binding Generator][generator]**._

## 6 JSONx Validator

The JSONx Validator consumes a JSD schema and a JSON document, and returns successfully if the specified documents are valid against the provided schema, or fails with an exception specifying the validation error if the specified document is invalid against the provided schema. The JSONx Validator utilizes the JSONx Binding Generator to perform its validation.

## 6.1 Purpose

Provide a validator utility for automatic validation of JSON documents against a schema document.

## 6.2 Requirements

1. The validator MUST be able to consume a JSON document, and validate its contents agains a provided schema document.

1. The validator MUST return successfully if a JSON document conforms to the provided schema document.

1. The validator MUST throw an exception specifying the validation error if a JSON document does not conform to the provided schema document.

## 6.3 Getting Started

The JSONx Validator provides convenience utilities for validating a JSON document agains a schema document. The following illustrates example usage of the `Validator`.

### 6.3.1 Valid Case

The following example uses the `Validator` to validate a valid JSON document against a schema document.

```bash
$ java -cp ... org.jsonx.Validator src/main/resources/example.jsd src/main/resources/valid.json
$ echo $?
0
```

### 6.3.2 Invalid Case

The following example uses the `Validator` to validate an invalid JSON document against a schema document.

```bash
$ java -cp ... org.jsonx.Validator src/main/resources/example.jsd src/main/resources/invalid.json
Invalid content was found in empty array: @org.jsonx.StringElement(id=0, pattern="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"): Content is not complete
$ echo $?
1
```

## 6.4 Specification

The `Validator` is a utility class that can be used on the CLI to validate a JSON document against a schema document. The `Validator` class has the following usage specification:

```
Usage: Usage: Validator
Supported SCHEMA formats:

```

## 7 JSONx Integration for JAX-RS

Implements the `MessageBodyReader` and `MessageBodyWriter` interfaces in the JAX-RS API to integrate with JAX-RS server runtimes.

### 7.1 Purpose

Provide JSONx Integration for JAX-RS for parsing and marshaling Java object instances of binding classes in a JAX-RS runtime.

### 7.2 Requirements

1. The JSONx Integration for JAX-RS MUST support validation of JSON upon the consumption and production of documents in a JAX-RS runtime.

1. The JSONx Integration for JAX-RS MUST support any JAX-RS application that implements the facets relevant to parsing and marshaling of entity object, as defined in the [JAX-RS 2.0 Specification](https://download.oracle.com/otn-pub/jcp/jaxrs-2_0-fr-eval-spec/jsr339-jaxrs-2.0-final-spec.pdf).

1. The JSONx Integration for JAX-RS MUST be automatic and free of any configuration that would couple an application to the JSONx Framework for Java.

### 7.3 Getting Started

The JSONx Integration for JAX-RS sub-project provides a `Provider` implementing the `MessageBodyReader` and `MessageBodyWriter` interfaces that can be registered with a JAX-RS runtime.

The following illustrates example usage.

  1. Create `account.jsd` or `account.jsdx` in `src/main/resources/`.

###### **JSD**

```json
{
"jx:ns": "http://www.jsonx.org/schema-0.4.jsd",
"jx:schemaLocation": "http://www.jsonx.org/schema-0.4.jsd http://www.jsonx.org/schema.jsd",

"uuid": { "jx:type": "string", "pattern": "[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}" },
"id": { "jx:type": "object", "abstract": true, "properties": {
"id": { "jx:type": "reference", "nullable": false, "type": "uuid" } } },
"credentials": { "jx:type": "object", "properties": {
"email": { "jx:type": "string", "nullable": false, "pattern": "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}" },
"password": { "jx:type": "string", "nullable": false, "pattern": "[0-9a-f]{64}", "use": "optional" } } },
"account": { "jx:type": "object", "extends": "credentials", "properties": {
"id": { "jx:type": "reference", "nullable": false, "type": "uuid", "use": "optional" },
"firstName": { "jx:type": "string", "nullable": false },
"lastName": { "jx:type": "string", "nullable": false } } }
}
```

###### **JSDx**

```xml













```

_**Note:** You can use the [Converter][#converter] utility to automatically convert between JSD and JSDx._

  2. Add the [`org.jsonx:jsonx-maven-plugin`][jsonx-maven-plugin] to the POM.

```xml

org.jsonx
jsonx-maven-plugin
0.4.0



generate


${project.build.directory}/generated-sources/jsonx
com.example.jsonx.

src/main/resources/account.jsonx



```

  3. Upon successful execution of the [`jsonx-maven-plugin`][jsonx-maven-plugin] plugin, Java class files will be generated in `generated-sources/jsonx`. Add this path to your Build Paths in your IDE to integrate into your project.

The generated classes can be instantiated as any other Java objects. They are strongly typed, and will guide you in proper construction of a JSON message. The following APIs can be used for parsing and marshalling JSONx to and from JSON:

To parse JSON to JSONx Bindings:

```java
String json = "{\"email\":\"john@doe\",\"password\":\"066b91577bc547e21aa329c74d74b0e53e29534d4cc0ad455abba050121a9557\"}";
Credentials credentials = JxDecoder.parseObject(Credentials.class, new JsonReader(new StringReader(json)));
```

To marshal JSONx Bindings to JSON:

```java
String json2 = JxEncoder.get().marshal(credentials);
assertEquals(json, json2);
```

  4. Next, register the `JxObjectProvider` provider in the JAX-RS appilcation singletons, and implement the `AccountService`:

```java
public class MyApplication extends javax.ws.rs.core.Application {
@Override
public Set getSingletons() {
return Collections.singleton(new JxObjectProvider(JxEncoder._2));
}
}

@Path("/account")
@RolesAllowed("registered")
public class AccountService {
@GET
@Produces("application/vnd.example.v1+json")
public Account get(@Context SecurityContext securityContext) {
Account account = new Account();
...
return account;
}

@POST
@Consumes("application/vnd.example.v1+json")
public void post(@Context SecurityContext securityContext, Account account) {
...
}
}
```

### 7.4 Specification

_For a detailed specification of JSONx Integration for JAX-RS, see **[JSONx Integration for JAX-RS][jaxrs]**._

## 8 JSONx Maven Plugin

A Maven plugin for generating JSONx and JSD bindings.

### 8.1 Purpose

Provide schema validation, schema conversion, and Java binding source generation in a Maven plugin.

### 8.2 Requirements

1. The JSONx Maven plugin MUST offer utilities for the generation of Java binding sources from a specified schema document.

1. The JSONx Maven plugin MUST offer utilities for validation of schema documents.

1. The JSONx Maven plugin MUST offer utilities for conversion of schema documents from JSD to JSDx, and vice versa.

1. The JSONx Maven plugin MUST present clear and informative errors and warnings that arise during parsing and validation of schema documents and JSON documents with an associated schema.

### 8.3 Getting Started

The JSONx Maven Plugin implements a Maven MOJO that can be used in a `pom.xml`. The following illustrates an example usage.

```xml

org.jsonx
jsonx-maven-plugin
0.4.0



generate

generate-sources

${project.build.directory}/generated-sources/jsonx
com.example.json.

src/main/resources/schema.jsd



```

### 8.4 Specification

_For a detailed specification of the Maven plugin, see **[JSONx Maven Plugin][jsonx-maven-plugin]**._

## 9 JsonXml

Offers facilities for converting JSON documents to XML, and vice-versa.

### 9.1 Purpose

Provide an encoding of JSON documents in an analogous form that uses XML semantics, referred to as JsonXml documents.

### 9.2 Requirements

1. The JsonXml documents MUST be able to represent any and all legal JSON documents, as specified by [RFC2119](https://www.ietf.org/rfc/rfc2119.txt).

1. The JsonXml documents MUST be translatable to JSON documents, and vice versa, preserving all normative and non-normative features of the original document.

1. The JsonXml documents MUST provide meaningful and useful validation features via XSD validation.

### 9.3 Getting Started

The JsonXml sub-project provides convenience utilities for converting JSON documents to XML. The following illustrates example usage of the `JxConverter` class.

#### 9.3.1 JSON-to-XML

```java
String xml = JxConverter.jsonToXml(new JsonReader(new FileReader("example.json")));
```

#### 9.3.2 XML-to-JSON

```java
String json = JxConverter.xmlToJson(new FileInputStream("example.xml"));
```

### 9.4 Specification

_For a detailed specification of JsonXml, see **[JsonXml][jsonxml]**._

## 10 Contributing

Pull requests are welcome. For major changes, please [open an issue](../../issues) first to discuss what you would like to change.

Please make sure to update tests as appropriate.

## 11 Special Thanks

[![Java Profiler](https://www.ej-technologies.com/images/product_banners/jprofiler_small.png)](https://www.ej-technologies.com/products/jprofiler/overview.html)

_Special thanks to [EJ Technologies](https://www.ej-technologies.com/) for providing their award winning Java Profiler ([JProfiler](https://www.ej-technologies.com/products/jprofiler/overview.html)) for development of the JSONx Framework._

## 12 License

This project is licensed under the MIT License - see the [LICENSE.txt](LICENSE.txt) file for details.

[#runtime]: #4-jsonx-runtime-api
[#converter]: #532-converter
[#invoice-example]: #43-getting-started
[#jsd]: #3-json-schema-definition-language

[runtime]: runtime
[generator]: generator
[validator]: validator
[jaxrs]: jaxrs
[jsonx-maven-plugin]: jsonx-maven-plugin
[jsonxml]: jsonxml
[sample-cdc]: sample/cdc
[sample-invoice]: sample/invoice
[sample]: sample
[schema]: ../../../schema/

[cdc]: http://martinfowler.com/articles/consumerDrivenContracts.html
[oxygenxml]: https://www.oxygenxml.com/xml_editor/download_oxygenxml_editor.html
[xmlschema]: http://www.w3.org/2001/XMLSchema