263. Getting, updating, and saving a JSON

In the previous problems, we manipulated JSON data as plaintext (strings). The HTTP Client API doesn't provide special or dedicated support for JSON data and treats this kind of data as any other string.

Nevertheless, we are used to representing JSON data as Java objects (POJOs) and relying on the conversion between JSON and Java when needed. We can write a solution to our problem without involving the HTTP Client API. However, we can also write a solution using a custom implementation of HttpResponse.BodyHandler that relies on a JSON parser to convert the response into Java objects. For example, we can rely on JSON-B (introduced in Chapter 6, Java I/O Paths, Files, Buffers, Scanning, and Formatting).

Implementing the HttpResponse.BodyHandler interface implies overriding the apply(HttpResponse.ResponseInfo responseInfo) method. Using this method, we can take the bytes from the response and convert them into a Java object. The code is as follows:

public class JsonBodyHandler<T> 
implements HttpResponse.BodyHandler<T> {

private final Jsonb jsonb;
private final Class<T> type;

private JsonBodyHandler(Jsonb jsonb, Class<T> type) {
this.jsonb = jsonb;
this.type = type;
}

public static <T> JsonBodyHandler<T>
jsonBodyHandler(Class<T> type) {
return jsonBodyHandler(JsonbBuilder.create(), type);
}

public static <T> JsonBodyHandler<T> jsonBodyHandler(
Jsonb jsonb, Class<T> type) {
return new JsonBodyHandler<>(jsonb, type);
}

@Override
public HttpResponse.BodySubscriber<T> apply(
HttpResponse.ResponseInfo responseInfo) {

return BodySubscribers.mapping(BodySubscribers.ofByteArray(),
byteArray -> this.jsonb.fromJson(
new ByteArrayInputStream(byteArray), this.type));
}
}

Let's assume that the JSON that we want to manipulate looks like the following (this is the response from the server):

{
"data": {
"id": 2,
"email": "[email protected]",
"first_name": "Janet",
"last_name": "Weaver",
"avatar": "https://s3.amazonaws.com/..."
}
}

The Java objects for representing this JSON are as follows:

public class User {

private Data data;
private String updatedAt;

// getters, setters and toString()
}

public class Data {

private Integer id;
private String email;

@JsonbProperty("first_name")
private String firstName;

@JsonbProperty("last_name")
private String lastName;

private String avatar;

// getters, setters and toString()
}

Now, let's see how we can manipulate the JSON in requests and responses.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.44.53