Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.


2 Answers

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);
like image 119
f.loris Avatar answered Oct 30 '25 18:10

f.loris


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;
like image 43
Michał Ziober Avatar answered Oct 30 '25 17:10

Michał Ziober