Nereides for javax.json

An object-oriented JSON wrapper for javax.json.

License

License

Categories

Categories

IDE Development Tools
GroupId

GroupId

com.vzurauskas.nereides
ArtifactId

ArtifactId

nereides-javax
Last Version

Last Version

1.1.1
Release Date

Release Date

Type

Type

jar
Description

Description

Nereides for javax.json
An object-oriented JSON wrapper for javax.json.
Project URL

Project URL

https://github.com/vzurauskas/nereides-javax
Source Code Management

Source Code Management

https://github.com/vzurauskas/nereides-javax/tree/master

Download nereides-javax

How to add to project

<!-- https://jarcasting.com/artifacts/com.vzurauskas.nereides/nereides-javax/ -->
<dependency>
    <groupId>com.vzurauskas.nereides</groupId>
    <artifactId>nereides-javax</artifactId>
    <version>1.1.1</version>
</dependency>
// https://jarcasting.com/artifacts/com.vzurauskas.nereides/nereides-javax/
implementation 'com.vzurauskas.nereides:nereides-javax:1.1.1'
// https://jarcasting.com/artifacts/com.vzurauskas.nereides/nereides-javax/
implementation ("com.vzurauskas.nereides:nereides-javax:1.1.1")
'com.vzurauskas.nereides:nereides-javax:jar:1.1.1'
<dependency org="com.vzurauskas.nereides" name="nereides-javax" rev="1.1.1">
  <artifact name="nereides-javax" type="jar" />
</dependency>
@Grapes(
@Grab(group='com.vzurauskas.nereides', module='nereides-javax', version='1.1.1')
)
libraryDependencies += "com.vzurauskas.nereides" % "nereides-javax" % "1.1.1"
[com.vzurauskas.nereides/nereides-javax "1.1.1"]

Dependencies

compile (2)

Group / Artifact Type Version
javax.json : javax.json-api jar 1.1.4
org.glassfish : javax.json jar 1.1.4

test (2)

Group / Artifact Type Version
org.junit.jupiter : junit-jupiter-api jar 5.3.1
org.junit.jupiter : junit-jupiter-engine jar 5.3.1

Project Modules

There are no modules declared in this project.

EO principles respected here DevOps By Rultor.com

CircleCI Codecov Hits-of-Code Maven Central License

Nereid* for javax.json is an object oriented JSON library wrapper for JSR 374 (JSON Processing) API. It allows developers to work with JSON documents in a purely object oriented way: everything is instantiated via constructors, there are no static methods, no nulls and no "mappers" or "builders". Most importantly, the core Json interface lends itself to easy custom implementations, making Nereides very extensible.

There is also a Nereid for jackson-databind.

*(Nereides are the sea nymphs who guided Jason's ship safely through the Wandering Rocks in his quest for the Golden Fleece.)

Available Nereides:
-- Nereid for Jackson (recommended)
-- Nereid for javax.json

Maven dependency

<dependency>
    <groupId>com.vzurauskas.nereides</groupId>
    <artifactId>nereides-javax</artifactId>
    <version>1.1.1</version>
</dependency>

Simple usage

Create new Json object

// From String:
String jsonAsString = "{\"nymph\": \"nereid\"}";
Json json = new Json.Of(jsonAsString);

// From InputStream:
InputStream stream = new ByteArrayInputStream(jsonAsString.getBytes());
json = new Json.Of(stream);

// From javax.json.JsonStructure:
JsonStructure structure = javax.json.Json.createReader(new StringReader(jsonAsString)).read();
json = new Json.Of(structure);

SmartJson

Once we have the Json object, to use it in various ways, the Smart Object pattern is employed.

// Convert it to String:
String textual = new SmartJson(json).textual();

// Convert it to pretty formatted String:
String pretty = new SmartJson(json).pretty();

// Convert it to byte array:
byte[] bytes = new SmartJson(json).byteArray();

// Get a String field value:
Optional<String> leaf = new SmartJson(json).leaf("nymph");

// Get a deeply nested Json:
SmartJson nested = new SmartJson(json).at("/path/to/nested/json");

MutableJson

While the main purpose of this library is to enable making custom implementations of the Json interface (see more on that below), if you need to quickly assemble a Json by hand, MutableJson can be used. This API has a very declarative notation.

Json json = new MutableJson().with(
    "ocean",
    new MutableJson().with(
        "nereid1",
        new MutableJson()
            .with("name", "Thetis")
            .with("hair", "black")
    ).with(
        "nereid2",
        new MutableJson()
            .with("name", "Actaea")
            .with("hair", "blonde")
    )
    .with("stormy", true)
);
System.out.println(new SmartJson(json).pretty());

The code above would print this:

{
  "ocean" : {
    "nereid1" : {
      "name" : "Thetis",
      "hair" : "black"
    },
    "nereid2" : {
      "name" : "Actaea",
      "hair" : "blonde"
    },
    "stormy" : true
  }
}

Custom implementations

If you have an object which needs to be able to display itself as JSON, sometimes it might be useful to just treat it as a JSON to begin with. In that case that object will have to implement a JSON interface. In most (all?) other libraries, JSON interfaces are huge, making it very difficult to implement them. With Nereides, all you need to do is provide the JSON representation in a stream of bytes. The easiest way to do this is to encapsulate another Json and delegate to it, or construct one on the spot.

Let's say we have a bank account which we need to display as JSON. We need its IBAN, nickname and balance, which (to make this a less trivial example) we get from another service. One way to implement it is this:

public final class BankAccount implements Json {
    private final String iban;
    private final String nickname;
    private final TransactionHistory transactions;

    // Constructor...

    public void makePayment(double amount) { /* Implementation... */ }
    // Other public methods...

    @Override
    public InputStream bytes() {
        return new MutableJson()
            .with("iban", iban)
            .with("nickname", nickname)
            .with("balance", transactions.balance(iban))
            .bytes();
    }
}

Even simpler way is to extend the JsonEnvelope, then you don't even need to implement bytes():

public final class BankAccount extends JsonEnvelope {
    public BankAccount(String iban, String nickname, TransactionHistory transactions) {
        super(new MutableJson()
            .with("iban", iban)
            .with("nickname", nickname)
            .with("balance", transactions.balance(iban))
        );
    }

    public void makePayment(double amount) { /* Implementation... */ }
    // Other public methods...
}

We can then make an HTTP response directly, e.g. with Spring:

return new ResponseEntity<>(
    new SmartJson(
        new BankAccount(iban, nickname, transactions)
    ).byteArray(),
    HttpStatus.OK
);

...or with Takes:

return new RsWithType(
    new RsWithStatus(
        new RsWithBody(
            new BankAccount(iban, nickname, transactions).bytes()
        ),
        200
    ),
    "application/json"
);

...or insert it in some JSON datastore:

accounts.insert(new BankAccount(iban, nickname));

...or compose it within a larger JSON:

Json accounts = new MutableJson()
    .with("name", "John")
    .with("surname", "Smith")
    .with("account", new BankAccount(iban, nickname));

Additional functionality

If available functionality in the current version of Nereid is not enough, the developer can always fall back to javax.json. Convert Json to JsonStructure, do what you need with it, and construct a new Json.

JsonStructure structure = new SmartJson(json).jsonStructure();
// Do stuff with structure using javax.json API.
Json updated = new Json.Of(structure);

Contributing

To contribute:

  1. Fork this repository.
  2. Clone your fork.
  3. Create a branch from master.
  4. Make changes in your branch.
  5. Make sure the build passes with mvn clean install -Pwall. ("wall" is Maven profile with quality wall)
  6. Commit and push your changes to your fork.
  7. Make a pull request from your fork to this repository.

You can read more about contributing in GitHub in this article.

Versions

Version
1.1.1
1.1.0
1.0.4
1.0.3
1.0.2
1.0.1
1.0.0
0.0.3
0.0.2
0.0.1