GSON:期望一个字符串,但是BEGIN_OBJECT? [英] GSON: Expected a string but was BEGIN_OBJECT?
本文介绍了GSON:期望一个字符串,但是BEGIN_OBJECT?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图用GSON来解析一些非常简单的JSON。这是我的代码:
Gson gson = new Gson();
InputStreamReader reader = new InputStreamReader(getJsonData(url));
String key = gson.fromJson(reader,String.class);
以下是从网址返回的JSON:
{
access_token:abcdefgh
}
我得到这个异常:
E / AndroidRuntime(19447):com.google.gson .JsonSyntaxException:java.lang.IllegalStateException:期望一个字符串,但是在第1行BEGIN_OBJECT第2列
任何想法? JSON结构是一个名为access_token的元素,它不仅仅是一个名为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 \};
地图< String,String> map = new Gson()。fromJson(jsonInput,new TypeToken< Map< String,String>>(){} .getType());
String key = map.get(access_token);
System.out.println(key);
$ b $ p
$ b另一种常用的方法是使用更具体的Java数据结构匹配JSON。例如:
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 \};
响应响应= new Gson()。fromJson(jsonInput,Response.class);
System.out.println(response.key);
类响应
{
@SerializedName(access_token)
字符串键;
}
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.
解决方案 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;
}
这篇关于GSON:期望一个字符串,但是BEGIN_OBJECT?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文