Brian Schmitz Brian Schmitz -4 years ago 121
Java Question

I get null fields when I try to deserialize JSON with GSON

The Gist

I tried to deserialize some JSON text with GSON. The JSON string had values defined. However, the deserialized string has null values.

Exactly what I did

I tried to deserialize some JSON text with GSON

SomeSpec deserializedJson = GSON.fromJson(serializedJson, SomeSpec.class);


where
serializedJson
is a string containing

{
"some_class": "abc.def.SomeClass",
"stuff": [
"FOO",
"BAR",
],
"definition": {
"values": [
{ "feature": "FOO", "value": 1.0 },
{ "feature": "BAR", "value": 1.0 },
]
}
}


and
SomeSpec
is a java class containing:

package somepackagepath;

import java.util.List;

public class SomeSpec {

private List<FeatureValueSpec> _values;
private List<String> _postProcessFunctions;

public List<FeatureValueSpec> getValues() {
return _values;
}

public List<String> getPostProcessFunctions() {
return _postProcessFunctions;
}

public static class FeatureValueSpec {
private String _feature;
private float _value;

public String getFeature() {
return _feature;
}

public float getValue() {
return _value;
}

}

}


The deserialized object had only null fields even though the JSON clearly had those fields defined.

Answer Source

First: There are two errors in your JSON in Arrays. There are extra commas at end of each array.

Second your models should look like this

public class Values
{
    private String value;

    private String feature;

    public String getValue ()
    {
        return value;
    }

    public void setValue (String value)
    {
        this.value = value;
    }

    public String getFeature ()
    {
        return feature;
    }

    public void setFeature (String feature)
    {
        this.feature = feature;
    }
}

public class Definition
{
    private Values[] values;

    public Values[] getValues ()
    {
        return values;
    }

    public void setValues (Values[] values)
    {
        this.values = values;
    }
}

public class MyPojo
{
    private Definition definition;

    private String[] stuff;

    private String some_class;

    public Definition getDefinition ()
    {
        return definition;
    }

    public void setDefinition (Definition definition)
    {
        this.definition = definition;
    }

    public String[] getStuff ()
    {
        return stuff;
    }

    public void setStuff (String[] stuff)
    {
        this.stuff = stuff;
    }

    public String getSome_class ()
    {
        return some_class;
    }

    public void setSome_class (String some_class)
    {
        this.some_class = some_class;
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download