确保您的原始 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 + "]";
}
}