When I try to run my project my game crash with this error:
Exception in thread "LWJGL Application" java.lang.NullPointerException
at com.badlogic.gdx.utils.Json.writeValue(Json.java:376)
at com.mygdx.game.MyGdxGame.write(MyGdxGame.java:30)
at com.mygdx.game.MyGdxGame.create(MyGdxGame.java:25)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:136)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:114)
And the code is:
private Json json;
private int x = 1;
@Override
public void create() {
json = new Json();
write(json);
}
@Override
public void write(Json json) {
json.writeValue("X", x);
}
What is the problem? I can't find the solution
Looking at the source code, it looks like the problem is that you haven't set a writer. It's not clear what you expect writeValue
to do when you haven't set a writer, but you either need to change which method you call (e.g. calling prettyPrint
instead), or set the writer first.
For example:
private Json json;
private StringWriter writer;
writer = new StringWriter();
json = new Json();
json.setWriter(writer);
write(json);
Then you can use writer.toString()
to get the JSON out later.
See more on this question at Stackoverflow