Ken Y-N
Ken Y-N

Reputation: 15009

Simplest Gson.fromJson example fails

Given the following code:

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

I get ret set to null.

I'm sure I've missed something obvious out, as toJson with a class also fails, although hand-construction through JsonObject works.

Upvotes: 5

Views: 4948

Answers (2)

Dennis Winter
Dennis Winter

Reputation: 2037

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

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

To retrieve the object back from the string:

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

Upvotes: 1

Rajesh
Rajesh

Reputation: 15774

Declare your class retVal outside the method.

Upvotes: 4

Related Questions