由于某种原因,我在解析JSON_STRING
的数据时遇到GSON
问题。当我尝试解析时,我返回null。你能帮我解下面的代码,并让我知道我错了哪里?我的目标是最终解析来自url的JSON提要,但我想要为测试目的对字符串进行硬编码。GSON解析字符串返回null?
import com.google.gson.Gson;
public class ReadJson {
public static void main(String... args) throws Exception {
String JSON_STRING =
"{\"data\":[{\"NAME\":\"Brandy\",\"LOCATION\":\"Redding, CA\"},
{\"NAME\":\"Jacob\",\"LOCATION\":\"Redding, CA\"},
{\"NAME\":\"Tatiana\",\"LOCATION\":\"Wonderland\"},
{\"NAME\":\"Tedo\",\"LOCATION\":\"Cottonwood\"}]}";
DataJSON data2 = new Gson().fromJson(JSON_STRING, DataJSON.class);
System.out.println(data2);
}
}
class DataJSON {
public String NAME;
public String LOCATION;
public String getName() { return NAME; }
public String getLocation() { return LOCATION;}
public void setName(String NAME) { this.NAME = NAME; }
public void setLoction(String LOCATION) { this.LOCATION = LOCATION; }
public String toString() {
return String.format("NAME:%s,LOCATION:%s", NAME, LOCATION);
}
}
我猜你不能直接打印data2。你有没有调试过这个项目并观看了data2的值? – 2013-05-11 04:38:33
看起来他已经在'DataJSON'类中使用了'toString()'!!! – NINCOMPOOP 2013-05-11 04:41:57
是的,你应该把@Override放在toString的顶部。 – 2013-05-11 04:44:16