Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplest Gson.fromJson example fails

Tags:

android

gson

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.

like image 202
Ken Y-N Avatar asked Jun 07 '12 07:06

Ken Y-N


People also ask

What does Gson fromJson do?

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.

Does Gson ignore extra fields?

As you can see, Gson will ignore the unknown fields and simply match the fields that it's able to.

Is Gson thread safe?

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.


2 Answers

Declare your class retVal outside the method.

like image 128
Rajesh Avatar answered Nov 06 '22 04:11

Rajesh


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);
like image 1
Dennis Winter Avatar answered Nov 06 '22 04:11

Dennis Winter