Skip to content

eo-cqrs/eokson

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

logo

Managed By Self XDSD

EO principles respected here DevOps By Rultor.com We recommend IntelliJ IDEA

mvn maven central javadoc codecov

Hits-of-Code Lines-of-Code PDD status License

Project architect: @h1alexbel

EOkson - Elegant, Object-Oriented JSON Manipulations.

Motivation. We are not happy dealing with JSON in procedural way.
We offer everything through simple, declarative objects.

Principles. These are the design principles behind EOkson.

How to use. All you need is this (get the latest version here):

Maven:

<dependency>
  <groupId>io.github.eo-cqrs</groupId>
  <artifactId>eokson</artifactId>
</dependency>

Gradle:

dependencies {
    compile 'io.github.eo-cqrs:eokson:<version>'
}

Create new Json object

you can create it from string:

Json json = new JsonOf("{\"chair\": \"Herman Miller Aeron\"}");

also, you can create JSON with Jackson's JsonNode:

JsonNode node = new ObjectMapper().readTree("{\"chair\": \"Herman Miller Aeron\"}");
json = new JsonOf(node);

or with file:

Json json = new JsonOf(path to file);

Jocument, smart JSON document

Textual representation:

String textual = new Jocument(json).textual();

Pretty textual representation:

String pretty = new Jocument(json).pretty();

Represent JSON as an array of bytes:

byte[] bytes = new Jocument(json).byteArray();
{
  "chair": "Herman Miller Aeron"
}

Get JSON field value:

String leaf = new Jocument(json).leaf("chair");

Output: Herman Miller Aeron.

Get a nested JSON:

{
  "amazon": {
    "shop": {
        "books": [
          {
            "name": "Code Complete",
            "price": 30
          },
          {
            "name": "PMP exam prep.",
            "price": 60
          }
        ]
      }
    }
  }
Jocument nested = new Jocument(json).at("/amazon/shop/books/0");

The result will be:

{
  "name": "Code Complete",
  "price": 30
}

Back to jackson-databind:

ObjectNode node = new Jocument(json).objectNode();
Json updated = new JsonOf(node);

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 Jocument(json).pretty());

The code above would print this:

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

Creating JSON with a nested array:

new Jocument(
  new MutableJson()
        .with(
          "amazon", new MutableJson()
            .with(
              "shop",
              new MutableJson()
                .with(
                  "books",
                  List.of(
                    new MutableJson()
                      .with("name", "Code Complete")
                      .with("price", 30),
                    new MutableJson()
                      .with("name", "PMP exam prep.")
                      .with("price", 60)
                  )
                )
            )
        )
).pretty();

It will print you following JSON document:

{
  "amazon": {
    "shop": {
      "books": [
        {
          "name": "Code Complete",
          "price": 30
        },
        {
          "name": "PMP exam prep.",
          "price": 60
        }
      ]
    }
  }
}

Implementing Json

You can implement your own JSON model using Json interface:

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

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

Or extending the JsonEnvelope:

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))
    );
  }
}

Integration with RESTful APIs

Here is the example of eokson usage with Spring Framework:

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

and using Takes:

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

Also, you can insert it in some JSON datastore:

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

JSON to XML

You can easily transform JSON to XML using JsonXML:

{
  "test": "true",
  "simple": "true",
  "project": "eokson-0.3.2"
}
final String xml = new JsonXML(new JsonOf(json), "root").asString();

here is XML output:

<?xml version='1.0' encoding='UTF-8'?>
<root>
  <test>true</test>
  <simple>true</simple>
  <project>eokson-0.3.2</project>
</root>

Also, you can integrate eokson with jcabi-xml:

import com.jcabi.xml.XMLDocument;
import com.jcabi.xml.XML;

final XML xml = new XMLDocument(
  new JsonXML(
    new JsonOf(
      json
    ),
    "test"
  ).asString()
);

How to Contribute

Fork repository, make changes, send us a pull request. We will review your changes and apply them to the master branch shortly, provided they don't violate our quality standards. To avoid frustration, before sending us your pull request please run full Maven build:

$ mvn clean install

You will need Maven 3.8.7+ and Java 17+.

Our rultor image for CI/CD.