bertvo bertvo - 1 year ago 78
Java Question

Lib Gdx json serializationexception and missing no-arg constructor

When trying to execute this piece of code:

public void load(String filename) {
FileHandle file = Gdx.files.external(filename + ".bim");
Json json = new Json();
String text = file.readString();
datamap = json.fromJson(HashMap.class, text);

I get an error:

Exception in thread "LWJGL Application"
com.badlogic.gdx.utils.SerializationException: Class cannot be created
(missing no-arg constructor): com.bvo.easyBim.Model.Cursor at
Caused by: com.badlogic.gdx.utils.SerializationException: Class cannot
be created (missing no-arg constructor): com.bvo.easyBim.Model.Cursor
at com.badlogic.gdx.utils.Json.newInstance( at
com.badlogic.gdx.utils.Json.readValue( at
com.badlogic.gdx.utils.Json.readValue( at
com.badlogic.gdx.utils.Json.fromJson( at
com.bvo.easyBim.View.DataProcessor.load( at
com.bvo.easyBim.View.World.init( at
com.bvo.easyBim.View.WorldRenderer.buttons( at
com.bvo.easyBim.View.WorldRenderer.render( at
com.bvo.easyBim.Screens.AppScreen.render( at
com.badlogic.gdx.Game.render( at
com.bvo.easyBim.EasyBim.render( at
Caused by: java.lang.InstantiationException:
com.bvo.easyBim.Model.Cursor at java.lang.Class.newInstance0(Unknown
Source) at java.lang.Class.newInstance(Unknown Source) at
com.badlogic.gdx.utils.Json.newInstance( ... 12 more

I am trying to translate the json file back into the datamap after It was correctly saved in another piece of code. ( A hashmap ) but this does not seem to work .

I am guessing that he is unable to read the text string, but I actually have no idea what the problem is.

Answer Source

The exception message "Class cannot be created (missing no-arg constructor): com.bvo.easyBim.Model.Cursor" describes exactly what is going wrong.

The Libgdx JSON code uses reflection to create instances of objects and initialize them. In your example, there must be a com.bvo.easyBim.Model.Cursor in the saved JSON file. So when reading that file, the JSON code needs to create an instance of a Cursor to put the data in. It assumes there is a no-argument constructor that it can use to create an empty Cursor (it cannot figure out which constructor would be appropriate otherwise). However, it seems that there is no such method.

You will either have to add a no-argument constructor to Cursor, or you will have to add a custom serializer (see that knows how to save a Cursor instance and knows the appropriate constructor to invoke when reading a Cursor back in.