Gson对象反序列化

时间:2013-04-17 12:52:04

标签: serialization gson

您能告诉我如何使用Gson提取此字符串中定义的两个不同对象: http://json.parser.online.fr/

我尝试使用

gson.fromJson(json, SeedAttribs.class);

gson.fromJson(json, SettingsAttribs.class);

但两者都没有效果。我很惊讶为什么不呢。 当特定对象例如,我还需要一种方法来替换这个json字符串。 SeedAttribs更改。我需要一种方法来重写它,而SettingsAttribs根本不会改变。

如何做到这一点?

感谢您的回答!

1 个答案:

答案 0 :(得分:0)

确保原始JSon字符串包含正确的格式。最好的方法是使用GSON序列化对象。这是代码:

public static void main(String[] args)
{
  Gson gson = new Gson();
  SettingsAttribs st = new SettingsAttribs();
  st.setField1("value1");
  st.setField2("value2");
  // report constructed object
  System.out.println("st: " + st);

  // serialize to json
  String json = gson.toJson(st, SettingsAttribs.class);
  System.out.println("json: " + json);

  // deserialize form json
  SettingsAttribs restoredSettings = gson.fromJson(json, SettingsAttribs.class);
  System.out.println("restoredSettings: " + restoredSettings);
}

它编译并运行。它产生的输出:

st: SettingsAttribs [field1=value1, field2=value2]
json: {"field1":"value1","field2":"value2"}
restoredSettings: SettingsAttribs [field1=value1, field2=value2]

和SettingsAttribs类:

  public class SettingsAttribs
  {
    private String field1;
    private String field2;

    public String getField1()
    {
      return field1;
    }

    public void setField1(String field1)
    {
      this.field1 = field1;
    }

    public String getField2()
    {
      return field2;
    }

    public void setField2(String field2)
    {
      this.field2 = field2;
    }

    @Override
    public String toString()
    {
      return "SettingsAttribs [field1=" + field1 + ", field2=" + field2 + "]";
    }
  }