This module provides support to application/json
using json-p, a Java spec to process json content.
json-p
does not serialize/deserialize JSON to/from POJOs like json-b
or jackson
; instead, json-p
has high-level objects to abstract over a JSON structure.
<dependency>
<groupId>com.github.ljtfreitas.julian-http-client</groupId>
<artifactId>julian-http-client-json-jsonp</artifactId>
<version>${julian-http-client-version}</version>
</dependency>
dependencies {
implementation("com.github.ljtfreitas.julian-http-client:julian-http-client-json-jsonp:$julianHttpClientVersion")
}
With the dependency in place, we can use a JsonObject or a JsonArray to write and read json content.
import javax.json.Json;
import javax.json.JsonObject;
import com.github.ljtfreitas.julian.contract.Path;
import com.github.ljtfreitas.julian.contract.GET;
import com.github.ljtfreitas.julian.contract.POST;
import com.github.ljtfreitas.julian.contract.Body;
@Path("/dogs")
interface DogsApi {
@POST
void create(@Body("application/json") JsonObject dogAsJson);
@GET
JsonArray allDogs();
}
DogsApi dogsApi = new ProxyBuilder().build(DogsApi.class, "http://my.dogs.api");
JsonObject dogAsJson = Json.createObjectBuilder()
.add("name", "Falco")
.add("age", 3)
.build();
dogsApi.create(dogAsJson);
JsonArray allDogs = dogsApi.allDogs();
allDogs.forEach(dog-> // ...);
julian-http-client uses JsonWriter and JsonReader in order to write and read json, and these objects are created using default configurations. Of course, we can customize both, building our own JsonWriterFactory and JsonReaderFactory:
import com.github.ljtfreitas.julian.ProxyBuilder;
import com.github.ljtfreitas.julian.http.codec.json.jsonp.JsonPHTTPMessageCodec;
import javax.json.Json;
import javax.json.JsonWriterFactory;
import javax.json.JsonReaderFactory;
Map<String, ?> configurations = //...
JsonWriterFactory jsonWriterFactory = Json.createWriterFactory(configurations);
JsonReaderFactory jsonReaderFactory = Json.createWriterFactory(configurations);
MyApi myApi = new ProxyBuilder()
.codecs()
.add(new JsonPHTTPMessageCodec(jsonReaderFactory,jsonWriterFactory))
.and()
.build(MyApi.class);