user5047085
user5047085

Reputation:

Best way to map JsonObject to class fields

I am using:

import io.vertx.core.json.JsonObject;

Say we have a class:

class Foo {
  public String barStar;
  public boolean myBool;
}

and then we have a JsonObject like so:

var o = new JsonObject(`{"bar_star":"yes","my_bool":true}`);

is there some built-in mechanism to map the JsonObject to the matching fields in the class? I am thinking of some sort of map instance, like so:

Foo f = o.mapTo(Foo.class, Map.of("bar_star","barStar","my_bool","myBool");

so you would pass in a map instance, and that would tell JsonObject how to map the fields? Can somehow show an example of how to do this? I specifically asking how to map the fields before deserializing to a class.

Upvotes: 4

Views: 5502

Answers (3)

f.loris
f.loris

Reputation: 1041

Vert.x has a mapTo method (see here). It is more efficient than the proposed solutions of encoding and decoding again when you already have a JsonObject.

Behind the scenes Jackson is used for mapping, so you can simply use @JsonProperty("...") to override the mapping of properties.

Your example would look as follows:

class Foo {
  @JsonProperty("bar_start")
  public String barStar;
  @JsonProperty("my_bool")
  public boolean myBool;
}

JsonObject obj = new JsonObject(`{"bar_star":"yes","my_bool":true}`);
Foo foo = obj.mapTo(Foo.class);

Upvotes: 7

Thomas Hirsch
Thomas Hirsch

Reputation: 2308

I created a small application that demonstrates this.
To make sense of everything it's probably best to just have a look at the whole codebase.
Find it at: https://github.com/thokari/epages-app-kickstart

I am posting some code, as is usually required on stackoverflow.
Here is the Model base class and a class that extends it:

package de.thokari.epages.app.model;

import io.vertx.core.json.Json;
import io.vertx.core.json.JsonObject;

public abstract class Model {

    public static <T extends Model> T fromJsonObject(JsonObject source, Class<T> clazz) {
        return Json.decodeValue(source.encode(), clazz);
    }

    public JsonObject toJsonObject() {
        return new JsonObject(Json.encode(this));
    }

    protected static <T> T validate(final String key, final T value) {
        if (null == value) {
            throw new IllegalArgumentException(key + " must not be null");
        } else {
            return (T) value;
        }
    }

    public String toString() {
        return Json.encode(this);
    }

}
package de.thokari.epages.app.model;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

import io.vertx.core.MultiMap;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;

public class InstallationRequest extends Model {

    private static final Logger LOG = LoggerFactory.getLogger(InstallationRequest.class);

    @JsonProperty("code")
    public String code;

    @JsonProperty("api_url")
    public String apiUrl;

    @JsonProperty("access_token_url")
    public String accessTokenUrl;

    @JsonProperty("return_url")
    public String returnUrl;

    @JsonProperty("token_path")
    public String tokenPath;

    @JsonProperty("signature")
    public String signature;

    @JsonCreator
    public InstallationRequest(
        @JsonProperty("code") String code,
        @JsonProperty("api_url") String apiUrl,
        @JsonProperty("access_token_url") String accessTokenUrl,
        @JsonProperty("return_url") String returnUrl,
        @JsonProperty("signature") String signature) {

        this.code = validate("code", code);
        this.apiUrl = validate("api_url", apiUrl);
        this.accessTokenUrl = validate("access_token_url", accessTokenUrl);
        this.returnUrl = validate("return_url", returnUrl);
        this.signature = validate("signature", signature);
        try {
            this.tokenPath = accessTokenUrl.substring(apiUrl.length());
        } catch (Exception e) {
            throw new IllegalArgumentException("access_token_url must contain api_url");
        }
    }

    public static InstallationRequest fromMultiMap(MultiMap source) {
        return new InstallationRequest(
            source.get("code"), //
            source.get("api_url"), //
            source.get("access_token_url"), //
            source.get("return_url"), //
            source.get("signature"));
    }

    public static InstallationRequest fromCallbackUrl(String callbackUrl) {
        String query = callbackUrl.split("\\?")[1];
        String[] parameters = query.split("&");
        String code = parameters[0].split("=")[1];

        String accessTokenUrl = parameters[1].split("=")[1];
        String urlEncodedSignature = parameters[2].split("=")[1];
        String signature = null;
        try {
            signature = URLDecoder.decode(urlEncodedSignature, "utf-8");
        } catch (UnsupportedEncodingException e) {
            LOG.error("Something went wrong because of a programming error");
        }

        // TODO why is this missing?!
        String apiUrl = accessTokenUrl.substring(0, accessTokenUrl.indexOf("/token"));

        return new InstallationRequest(code, apiUrl, accessTokenUrl, "not_needed", signature);
    }

    public Boolean hasValidSignature(String secret) {
        String algorithm = "HmacSHA256";
        String encoding = "utf-8";
        Mac mac;
        try {
            mac = Mac.getInstance(algorithm);
            mac.init(new SecretKeySpec(secret.getBytes(encoding), algorithm));
        } catch (NoSuchAlgorithmException | InvalidKeyException | UnsupportedEncodingException e) {
            LOG.error("Signature validation failed because of programming error", e);
            return false;
        }

        byte[] rawSignature = mac.doFinal((this.code + ":" + this.accessTokenUrl).getBytes());
        String signature = Base64.getEncoder().encodeToString(rawSignature);

        return this.signature.equals(signature);
    }
}

Upvotes: 0

Michał Ziober
Michał Ziober

Reputation: 38635

Jackson databind documentation describe how to convert String payload to POJO, Map to POJO and others. Take a look on readValue and convertValue methods from ObjectMapper.

EDIT
You have only one problem with naming convention. POJO properties do not fit to JSON. You need to use SNAKE_CASE naming strategy or JsonProperty annotation over property:

String json = "{\"bar_star\":\"yes\",\"my_bool\":true}";
ObjectMapper mapper = new ObjectMapper();
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);

JsonNode node = mapper.readTree(json);
System.out.println("Node: " + node);
System.out.println("Convert node to Foo: " + mapper.convertValue(node, Foo.class));
System.out.println("Deserialise JSON to Foo: " + mapper.readValue(json, Foo.class));

Above code prints:

Node: {"bar_star":"yes","my_bool":true}
Convert node to Foo: Foo{barStar='yes', myBool=true}
Deserialise JSON to Foo: Foo{barStar='yes', myBool=true}

JsonProperty you can use as below:

@JsonProperty("bar_star")
public String barStar;

Upvotes: 1

Related Questions