2012-07-20 212 views
15

我想用GSON來解析一些非常簡單的JSON。這裏是我的代碼:GSON:期望一個字符串,但是BEGIN_OBJECT?

Gson gson = new Gson(); 

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

這裏的JSON從URL返回:

{ 
    "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的新手。

回答

23

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

尼斯答案布魯斯! – 2012-07-20 12:43:59

+0

我可以打一箇舊的線程,新的Json,你可以簡要解釋一下你的第一個答案,我很困惑把Map放入類型token ..關於** fromJson()的第二個參數**()**方法 – SSH 2015-07-28 11:01:40

4

另一個「低級別」的可能性使用GSON JsonParser:

package stackoverflow.questions.q11571412; 

import com.google.gson.*; 

public class GsonFooWithParser 
{ 
    public static void main(String[] args) 
    { 
    String jsonInput = "{\"access_token\": \"abcdefgh\"}"; 

    JsonElement je = new JsonParser().parse(jsonInput); 

    String value = je.getAsJsonObject().get("access_token").getAsString(); 
    System.out.println(value); 
    } 
} 

如果有一天,你會寫一個自定義解串器,JsonElement將是你最好的朋友。

+1

Ty。我正在做這種確切的事情,需要這個確切的解決方案。 – Shadoninja 2016-04-13 16:45:32

+0

不客氣 – giampaolo 2016-04-13 18:06:23

相關問題