【发布时间】:2013-05-11 04:25:23
【问题描述】:
由于某种原因,我在 GSON 解析来自 JSON_STRING 的数据时遇到问题。当我尝试解析时,我返回 null。你能帮我写下下面的代码,让我知道我哪里出错了吗?我的目标是最终从 url 解析 JSON 提要,但我想对字符串进行硬编码以进行测试。
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 的值?
-
看来他在
DataJSON类中覆盖了toString()!!! -
是的,您应该将@Override 放在 toString 的顶部。
-
我是在 Stackoverflow 上发布问题的新手。我的问题是-1,我能做些什么来问一个更合适的庄园?