Skip to content

BespokeOutputTypesExample

Glythcing edited this page Sep 17, 2018 · 2 revisions

Tranquil can use the underlying JSON de/serialization library's features to convert an input into:

  • A specific Java type
  • A List of specific Java type

Given

JSON
[
  {
    "name": "tap",
    "price": 49.99,
    "quantity": 10,
    "active": true,
    "owner": null,
    "since": "2018-09-07"
  },
  {
    "name": "sink",
    "price": 99.99,
    "quantity": 100,
    "active": false,
    "owner": null,
    "since": "2018-09-02"
  }
]
Java Type
public class Item {
  private String name;
  private int quantity;

  public Item() {}

  public Item(String name, int quantity) {
    this.name = name;
    this.quantity = quantity;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public int getQuantity() {
    return quantity;
  }

  public void setQuantity(int quantity) {
    this.quantity = quantity;
  }
}

Read A Specific Java Type

The following example shows the use of Tranquil to:

  • Filter JSON by applying predicates
  • Shape JSON by applying projections
  • Map the transformed input to a custom Java type
When
Item item = Tranquil.parse(json).read("name, quantity", "name='tap'", Item.class);
Then

Tranquil will return an instance of Item with name=tap, quantity=10

Read A Collection Of Java Type

The following example shows the use of Tranquil to:

  • Filter JSON by applying predicates
  • Shape JSON by applying projections
  • Map the transformed input to a collection of custom Java type
When
TypeRef<List<Item>> type = new TypeRef<List<Item>>() {};

List<Item> read = Tranquil.parse(JSON_ARRAY).read("name, quantity", "name!='bath'", type);
Then

Tranquil will return a collection containing two instances of Item with the following contents:

  • name=tap, quantity=10
  • name=sink, quantity=100