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.
A Gson is a library for java and it can be used to generate a JSON. We can use the fromJson() method of Gson to parse JSON string into java object and use the toJson() method of Gson to convert Java objects into JSON string.
As you can see, Gson will ignore the unknown fields and simply match the fields that it's able to.
Gson is typically used by first constructing a Gson instance and then invoking toJson(Object) or fromJson(String, Class) methods on it. Gson instances are Thread-safe so you can reuse them freely across multiple threads.
Declare your class retVal
outside the method.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With