我正在尝试使用 GSON 来解析一些非常简单的 JSON。这是我的代码:
Gson gson = new Gson();
InputStreamReader reader = new InputStreamReader(getJsonData(url));
String key = gson.fromJson(reader, String.class);
这是从 url 返回的 JSON:
{
"access_token": "abcdefgh"
}
我遇到了这个异常:
E/AndroidRuntime(19447): com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 2
有什么想法吗?我是 GSON 的新手。
最佳答案
JSON 结构是一个包含一个名为“access_token”的元素的对象——它不仅仅是一个简单的字符串。可以将其反序列化为匹配的 Java 数据结构,例如 Map,如下所示。
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class GsonFoo
{
public static void main(String[] args)
{
String jsonInput = "{\"access_token\": \"abcdefgh\"}";
Map<String, String> map = new Gson().fromJson(jsonInput, new TypeToken<Map<String, String>>() {}.getType());
String key = map.get("access_token");
System.out.println(key);
}
}
另一种常见的方法是使用与 JSON 匹配的更具体的 Java 数据结构。例如:
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
public class GsonFoo
{
public static void main(String[] args)
{
String jsonInput = "{\"access_token\": \"abcdefgh\"}";
Response response = new Gson().fromJson(jsonInput, Response.class);
System.out.println(response.key);
}
}
class Response
{
@SerializedName("access_token")
String key;
}
关于android - GSON:期望一个字符串,但是是 BEGIN_OBJECT?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11571412/