An example of the simplest Gson.fromJson does not work

Given the following code:

final class retVal { int photo_id; }
Gson gson = new Gson();
retVal ret = gson.fromJson("{\"photo_id\":\"383\"}", retVal.class);

I bet reton null.

I'm sure I missed something obvious, since the toJsonclass also fails, although the manual construction through works JsonObject.

+5
source share
2 answers

Declare your class retValoutside the method.

+5
source

Gson helps you serialize objects. So first you need an object. Based on your approach, you want to do something like

RetVal myRetVal = new RetVal();
Gson gson = new Gson();
String gsonString = gson.toJson(myRetVal);

To return an object back from a string:

Gson gson = new Gson();
RetVal myNewRetValObj = gson.fromJson(gsonString, RetVal.class);
+1
source

All Articles