0

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

我尝试使用

gson.fromJson(json, SeedAttribs.class);

gson.fromJson(json, SettingsAttribs.class);

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

如何才能做到这一点?

谢谢你的回答!

4

1 回答 1

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 + "]";
    }
  }
于 2013-04-19T15:16:12.737 回答