android - GSON:期望一个字符串,但是是 BEGIN_OBJECT?

标签 android json gson

我正在尝试使用 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/

相关文章:

android - Ubuntu 10.04 和 Android 1.5 的 Ad hoc 网络

android - 将插件升级到3.0.0时,Gradle构建错误(manifestOutputFile)

java - 我如何退出我的应用程序?

javascript - JSON 中第 6 位的意外标记 i - React redux 应用程序

javascript - ASP.Net - 无效的 Json 字符串

android - 如何在android中隐藏首选项 fragment 的标题栏?

json - swift:无法使用存储的属性 'tableView' 覆盖

java - 将 DateTimeOffset 从 Android 发送到 .NET Web API

java - JsonParseException 反序列化对象失败

java - 如何在反序列化方法中从json对象获取字符串数组