Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
511 views
in Technique[技术] by (71.8m points)

android - GSON: Expected a string but was BEGIN_OBJECT?

I'm trying to use GSON to parse some very simple JSON. Here's my code:

    Gson gson = new Gson();

    InputStreamReader reader = new InputStreamReader(getJsonData(url));
    String key = gson.fromJson(reader, String.class);

Here's the JSON returned from the url:

{
  "access_token": "abcdefgh"
}

I'm getting this exception:

E/AndroidRuntime(19447): com.google.gson.JsonSyntaxException:     java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 2

Any ideas? I'm new to GSON.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The JSON structure is an object with one element named "access_token" -- it's not just a simple string. It could be deserialized to a matching Java data structure, such as a Map, as follows.

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);
  }
}

Another common approach is to use a more specific Java data structure that matches the JSON. For example:

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...