当我尝试使用GSON反序列化JSON时,我得到空字段

时间:2017-03-23 16:24:17

标签: java json serialization gson deserialization

要点

我尝试用GSON反序列化一些JSON文本。 JSON字符串已定义值。但是,反序列化的字符串具有空值。

正是我所做的

我尝试用GSON反序列化一些JSON文本

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

其中serializedJson是包含

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

SomeSpec是一个包含以下内容的java类:

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;
    }

  }

}

反序列化对象只有空字段,即使JSON明确定义了这些字段。

1 个答案:

答案 0 :(得分:1)

首先:您的JSON在数组中有两个错误。每个数组末尾都有额外的逗号。

其次你的模型应该是这样的

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;
    }
}