Skip to content

Latest commit

 

History

History
126 lines (87 loc) · 3.34 KB

README.md

File metadata and controls

126 lines (87 loc) · 3.34 KB

e-gson

This is a Json codec implementation for E and EOr types based on gson. It provides gson's JsonDeserializers and JsonSerializers as well as e's own Codec (see e-java docs).

Installation

If you use Gradle, add following to your project's build.gradle:

dependencies {
  implementation('dev.akif:e-gson:3.0.1')
}

If you use Maven, add following to your pom.xml:

<dependencies>
  <dependency>
    <groupId>dev.akif</groupId>
    <artifactId>e-gson</artifactId>
    <version>3.0.1</version>
  </dependency>
</dependencies>

If you use SBT, add following to your build.sbt:

libraryDependencies += "dev.akif" % "e-gson" % "3.0.1"

Contents

Below are some details and examples of e-gson's content. For more, please check corresponding automated tests and e-gson's documentation.

To get started, add following import which will cover all your needs:

import e.gson.*;

1. EGsonCodec

1.1. Decoding an E

Decoding a Json as E yields EOr<E> whose error is the decoding failure. If the decoding succeeds, the provided value is the decoded E.

import e.java.*;
import e.gson.*;
import com.google.gson.*;

EGsonCodec codec = EGsonCodec.get();

EOr<E> e1 = codec.decode(new JsonArray());
// Decoding failure, also an E
// {"name":"decoding-error","message":"Failed to decode!","causes":[{"message":"Excepted: JsonObject"}]}

EOr<E> e2 = codec.decode(new JsonObject());
// Decodes as `E.empty`
// {}

JsonObject o = new JsonObject();
o.add("code",    new JsonPrimitive(1));
o.add("name",    new JsonPrimitive("test-name"));
o.add("message", new JsonPrimitive("Test Message"));

EOr<E> e3 = codec.decode(o);
// Decoded E
// {"code":1,"name":"test-name","message":"Test Message"}

1.2. Encoding an E

import e.java.*;
import e.gson.*;
import com.google.gson.*;

EGsonCodec codec = EGsonCodec.get();

JsonElement j1 = codec.encode(E.empty);
// {}

JsonElement j2 = encode(E.fromName("test").message("Test").cause(E.fromCode(1)));
// {"name":"test","message":"Test","causes":[{"code":1}]}

2. EOrGsonCodec

e-gson provides implementations so that regular gson decoding can be done. However, it also provides e's own Codec. Using this is convenient as it reports decoding failures as E errors.

2.1. Decoding a Value

import e.java.*;
import e.gson.*;
import com.google.gson.*;

EOrGsonCodec<String> codec = new EOrGsonCodec<>(new Gson(), String.class);

EOr<String> eor1 = codec.decode(new JsonPrimitive(42));
// {"name":"decoding-error","message":"Failed to decode!"}

EOr<String> eor2 = codec.decode(new JsonPrimitive("test"));
// "test"

2.2. Encoding a Value

import e.java.*;
import e.gson.*;
import com.google.gson.*;

EOrGsonCodec<String> codec = new EOrGsonCodec<>(new Gson(), String.class);

JsonElement j1 = codec.encode(E.fromName("test").toEOr<String>());
// {"name":"test"}

JsonElement j2 = codec.encode(new EOr<String>("123"));
// "123"