BHuelse BHuelse - 3 years ago 137
Android Question

Deserialize with gson and null values

I am trying to deserialize my own class with a null value. But my code doesn't work.

My json:

{"Text":null,"Code":0,"Title":"This is Sparta!"}

In my method I do the following:

this.setText(gson.fromJson(jsonObject.getString("Text"), String.class));
this.setTitle(gson.fromJson(jsonObject.getString("Title"), String.class));
this.setCode(gson.fromJson(jsonObject.getString("Faccode"), Integer.class))

I am not deserialize the whole object, because there can be a
, too.

The error:

myapp W/System.err? Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 6 path $
myapp W/System.err? at
myapp W/System.err? at
myapp W/System.err? at
myapp W/System.err? at

Answer Source

First, you must read about how to parse using gson. You can find some example here.

Now you know how to parse, you can still have problem with null values. To solve it you must tell gson to (de)serialize null using

Gson gson = new GsonBuilder().serializeNulls().create();

From the serializeNulls() doc

Configure Gson to serialize null fields. By default, Gson omits all fields that are null during serialization.

EDIT (Not tested, based on doc)

In order to get some distinct value you can do

String json = ""; //Your json has a String
JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();

//If null, use a default value
JsonElement nullableText = jsonObject.get("Text");
String text = (nullableText instanceof JsonNull) ? "" : nullableText.getAsString();

String title = jsonObject.get("Title").toString();
int code = jsonObject.get("Code").getAsInt();

Otherwise if you have this pojo

public class MyElement {
    private String text;

    private String title;

    private int code;

you can parse using

String json = ""; //Your json has a String
Gson gson = new GsonBuilder().serializeNulls().create();
MyElement myElement = gson.fromJson(json, MyElement.class);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download