JSON Gson Serializer and Deserializer
Alternative option to work with JSON in Java is to use Google Gson open source library.
Use GsonSerializer and GsonDeserializer to serialize and deserialize Java Gson JSON object to and from the Candid payload of type RECORD.
A fully functional example using GsonSerializer and GsonDeserializer can be found here.
This example uses Motoko to call the canister main.mo. The canister uses 2 complex types, LoanApplication and LoanOffer.
// Loan Application
public type LoanApplication = {
id: Nat;
firstname: Text;
lastname: Text;
zipcode: Text;
ssn: Text;
amount: Float;
term: Nat16;
created: Int;
};
// Loan Offer
public type LoanOffer = {
providerid: Principal;
providername: Text;
applicationid: Nat;
apr: Float;
created: Int;
};The canister has 2 methods: apply and getOffers.
The example uses the file with JSON LoanApplication payload as an input.
To be able to properly map JSON names and values to Candid name types declare the IDLType structure as follows:
Next, create IDLValue using the GsonSerializer create method.
The Serializer input is the variable type JsonElement.
Use UpdateBuilder, QueryBuilder or Raw Methods to call the Canister and deserialize output to JsonElement.
Last updated