banner



Forgot To Register A Type Adapter?

How to Serialize and Deserialize Interfaces in Coffee Using Gson

Writer: Mauricio Silva Manrique


What is Gson?

Gson is a Java Library widely used to catechumen Java Objects into their JSON representation and vice versa.

Getting Started

Permit'south start by creating a new Coffee project. We tin can call data applied science "InterfaceSerialization".

We need to add the gson library in our projection in gild for united states of america to use data technology. If you are using Maven, add the latest version of gson to the POM file.

<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.3.1</version> </dependency>          

Stride i:

Now, allow'due south create our Java interface. This time I will be using "Cars" as an example. I dearest cars, who doesn't?

Our interface declares 3 features that all cars share.

public interface Automobile {     Cord model();     int maxSpeed();     Cord type(); }          

Footstep 2:

Let's at present create our Java classes that volition implement our "Car" interface. I will be using "Lexus" and "Acura" (my favorite brands) for this case.

Let'due south define our Lexus class:

public grade Lexus implements Motorcar {      individual int maxSpeed;     private String type;     private int rankingAmongSedans;     individual String model;      public Lexus(Cord model, int maxSpeed, String type, int rankingAmongSedans) {       this.model = model;       this.maxSpeed = maxSpeed;       this.blazon = blazon;       this.rankingAmongSedans = rankingAmongSedans;     }     public String model() {         render model;     }     public int maxSpeed() {         return maxSpeed;     }     public String type() {         render type;     }     public int getRankingAmongSedans() {         return rankingAmongSedans;     }     @Override     public String toString(){         return "Model: " + model + ", Max speed: " + maxSpeed + " km/h, Type: " + type + ", Ranking: " + rankingAmongSedans ;     } }          

Step 3:

In the aforementioned way nosotros take to ascertain our Acura class

public grade Acura implements Motorcar{     private int maxSpeed;     private String blazon;     private Cord model;      public Acura(String model, int maxSpeed, Cord type) {         this.model = model;         this.maxSpeed = maxSpeed;         this.blazon = blazon;     }     public String model() {         return aught;     }     public int maxSpeed() {         render maxSpeed;     }     public String type() {         render blazon;     }     @Override     public String toString() {         return "Model: " + model + ", Max speed: " + maxSpeed + " km/h, Type: " + type;     } }          

Notice that the Lexus grade contains an extra field chosen "rankingAmongSedans". This volition aid u.s.a. to distinguish between the two and prove that our serialization works properly.

Stride 4:

Now allow'southward define our test form:

public class Test {      public static void master(Cord[] args) {          //Allow'southward initialize our sample array of cars         Car cars[] = new Car[]{new Lexus("Lexus Is", 260, "Sedan", three), new Acura("Acura Mdx", 193, "Suv")};         //Create our gson case         Gson gson = new Gson();         //Let'due south serialize our array          Cord carsJsonFormat = gson.toJson(cars, Machine[].course);         //Let'southward Impress our serialized arrya          Organization.out.println("Cars in Json Format: " + carsJsonFormat);     } }          

In this form, we are basically creating an array of "Cars" with two auto objects, one being of Class Blazon Lexus, and the other i of Class Type Acura

So we instantiate a gson object chosen "Gson" and continue to serialize our array. Finally nosotros impress our array in JSON format.

Our output should look like this:

Cars in JSON format:

[{"maxSpeed":260,"blazon":"Sedan","rankingAmongSedans":iii,"model":"Lexus Is"},{"maxSpeed":193,"blazon":"Suv","model":"Acura Mdx"}]          

It seems that everything went fine, our array of cars is printed in JSON format; all the same, what happens when nosotros try to deserialize the String back to an array of Machine Objects?

Let's add this line lawmaking afterwards our print statement and endeavour to re run our test again.

Car [] carJsonArray = gson.fromJson(carsJsonFormat, Automobile[].class);          

Oops, did y'all get this? RunTimeException: "Unable to invoke no-args constructor for interface Auto. Annals an InstanceCreator with Gson for this blazon may fix this problem."

Serialize and Deserialize Interfaces in Java
click to view in a new tab

Gson doesn't take way to identify which "Auto Object" we are trying to deserialize. Nosotros need to annals a Type Adapter that will assist gson differentiate the objects.

Footstep 5: (The solution)

So allow's ascertain a Generic Interface Adapter (so we are non merely restricted to our car interface) that will override serialize and deserialize methods.

The magic happens in this class, as nosotros define a mapping structure to distinguish our Car Objects, where "CLASSNAME" is the key to get the object'south grade proper noun, and "Data" is the key that maps the actual JSON object.

public grade InterfaceAdapter              implements JsonSerializer, JsonDeserializer{      private static terminal String CLASSNAME = "CLASSNAME";     private static final Cord Information = "Information";      public T deserialize(JsonElement jsonElement, Type type,         JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {          JsonObject jsonObject = jsonElement.getAsJsonObject();         JsonPrimitive prim = (JsonPrimitive) jsonObject.get(CLASSNAME);         String className = prim.getAsString();         Class                                   klass = getObjectClass(className);             render jsonDeserializationContext.deserialize(jsonObject.get(Information), klass);         }         public JsonElement serialize(T jsonElement, Type blazon, JsonSerializationContext jsonSerializationContext) {             JsonObject jsonObject = new JsonObject();             jsonObject.addProperty(CLASSNAME, jsonElement.getClass().getName());             jsonObject.add(Information, jsonSerializationContext.serialize(jsonElement));             render jsonObject;         }     /****** Helper method to go the className of the object to exist deserialized *****/         public Class                                   getObjectClass(Cord className) {             try {                 return Class.forName(className);                 } catch (ClassNotFoundException eastward) {                     //eastward.printStackTrace();                     throw new JsonParseException(eastward.getMessage());                 }         }     } }                                                    

Step half-dozen:

Now, permit'south go dorsum to our exam class and add together the registerTypeAdapter to our gson object. Since nosotros are using a customized gson object, we demand to construct it with "gsonBuilder".

Let's supervene upon Gson gson = new Gson(); with:

//Create our gson instance GsonBuilder builder = new GsonBuilder(); architect.registerTypeAdapter(Machine.class, new InterfaceAdapter()); Gson gson = builder.create();                      

Now that we have registered our InterfaceAdapter, we'll add these lines of lawmaking to impress our results:

//Let's print our car objects to verify System.out.println("\n**********************************************************************"); Organization.out.println("My favorite Cars of 2015"); for(Car aCar : carJsonArray){     Organization.out.println(aCar); }   Organisation.out.println("**********************************************************************");          

Let'southward test again and see what happens. Afterward running our exam grade, nosotros should encounter the post-obit output: Cars in JSON Format:

[{"CLASSNAME":"Lexus","Information":{"maxSpeed":260,"type":"Sedan","rankingAmongSedans":3,"model":"Lexus Is"}},{"CLASSNAME":"Acura","Information":{"maxSpeed":193,"type":"Suv","model":"Acura Mdx"}} ]          

**********************************************************************

My favorite Cars of 2015

Model: Lexus Is, Max speed: 260 km/h, Type: Sedan, Ranking: 3

Model: Acura Mdx, Max speed: 193 km/h, Blazon: Suv

**********************************************************************

Nosotros were able to accomplish our goal using gson past simply adding an interface adapter. It's upwards to you how to customize the serialization of unlike data types.

Source: https://technology.finra.org/code/serialize-deserialize-interfaces-in-java.html

Forgot To Register A Type Adapter?,

Source: https://damicopriout37.blogspot.com/2022/04/gson-forgot-to-register-type-adapter.html

Posted by: mullettrivinquister.blogspot.com

0 Response to "Forgot To Register A Type Adapter?"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel