2017-08-15 80 views
0

我有JSON應答,其看起來像這樣:解析JSONArray含有原始和對象

{ 
    "response":[ 
     "Some number (for example 8091)", 
     { 
     "Bunch of primitives inside the first JSONObject" 
     }, 
     { 
     "Bunch of primitives inside the second JSONObject" 
     }, 
     { 
     "Bunch of primitives inside the third JSONObject" 
     }, 

     ... (and so on) 

    ] 
} 

因此,它是與第一整數元素和其他元素的數組是的JSONObject。 我不需要整數元素來解析。那麼我如何使用GSON來處理它?

+1

這是一個無效JSON文檔。你能粘貼真實的迴應嗎? –

+1

這是真實的 - https://pastebin.com/uW9qBa6s。對不起,無法顯示請求導致它使用令牌。 –

+0

感謝您的幫助。看到我的回答,並讓我知道它是否有效 –

回答

1

我會通過創建一個自定義JsonDeserializer並在解析之前將其註冊到您的Gson實例來解決此問題。這個自定義解串器將被設置爲處理int和真實對象。

首先,您需要建立一系列模型對象來表示數據。下面是什麼,可能看起來像一個模板:

private static class TopLevel { 

    @SerializedName("response") 
    private final List<ResponseElement> elements; 

    private TopLevel() { 
     this.elements = null; 
    } 
} 

private static class ResponseInteger implements ResponseElement { 

    private final int value; 

    public ResponseInteger(int value) { 
     this.value = value; 
    } 
} 

private static class ResponseObject implements ResponseElement { 

    @SerializedName("id") 
    private final String id; 

    @SerializedName("text") 
    private final String text; 

    private ResponseObject() { 
     this.id = null; 
     this.text = null; 
    } 
} 

private interface ResponseElement { 
    // marker interface 
} 

TopLevelResponseObject有私有的構造,因爲它們將讓GSON使用反射設置各自的領域,而ResponseInteger有一個公共的構造函數,因爲我們要手動調用它來自我們的自定義解串器。

顯然你必須填寫ResponseObject與其餘的領域。

解串器相對簡單。你發佈的json只包含兩種元素,我們將利用它。每次調用解串器時,它都會檢查元素是否爲基元,如果是(否則返回ResponseInteger),否則返回ResponseInteger(否則返回ResponseObject)。

private static class ResponseElementDeserializer implements JsonDeserializer<ResponseElement> { 

    @Override 
    public ResponseElement deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { 
     if (json.isJsonPrimitive()) { 
      return new ResponseInteger(json.getAsInt()); 
     } 
     else { 
      return context.deserialize(json, ResponseObject.class); 
     } 
    } 
} 

要使用此解串器,你就必須使用GsonBuilder對象與GSON進行註冊。

private static Gson getGson() { 
    return new GsonBuilder() 
      .registerTypeAdapter(ResponseElement.class, new ResponseElementDeserializer()) 
      .create(); 
} 

就是這樣。現在你可以使用這個Gson對象來輕鬆解析TopLevel對象!

public void parseJson() { 
    TopLevel t = getGson().fromJson(json, TopLevel.class); 

    for (ResponseElement element : t.elements) { 
     System.out.println(element); 
    } 
} 
8061 
[450602: Поздравляем!] 
[451700: С реакцией чата и рассуждениями Папани после рипа..] 
[451578: Помним...Любим...Скорбим...<br>2107 забирает лучших] 
[451371: Земля тебе пухом братишка] 
[451332: Доигрался, минус 900 экзов<br><br>R I P] 
[451269: ] 
[451242: https://www.twitch.tv/arthas подрубка<br><br>evilpapech.ru - скидка 30% на футболки!] 
[451217: ] 
[451181: или так це жерстко?] 
[451108: ] 

我用這些toString()方法,這是我以上爲簡潔起見省略:

@Override 
    public String toString() { 
     return Integer.toString(value); 
    } 

    @Override 
    public String toString() { 
     return "[" + id + ": " + text + "]"; 
    } 
0

基本上這個結構是JSON數據的錯誤格式。 您需要刪除數字,或將此數字作爲字段放在同一個對象中(如下所示)(調用ObjectA),並將其視爲ObjectA的數組。 然後一切都應該很好。試試下面的代碼:

public class Response { 
    @SerializedName("response") 
    @Expose 
    public List<ObjectA> objectA = null; 
} 

public class ObjectA { 
    @SerializedName("value") 
    @Expose 
    public Integer value; 
    @SerializedName("description") 
    @Expose 
    public String description; 
} 

Response response = new Gson().fromJson(responseString, Response.class); 
0

試試這個

Gson gson = new Gson(); 

// Reading from a file. 
Example example = gson.fromJson(new FileReader("D:\\content.json"), Example.class); 

POJO

package com.example; 

public class Example { 

private List<Integer> response = null; 

public List<Integer> getResponse() { 
return response; 
} 

public void setResponse(List<Integer> response) { 
this.response = response; 
} 

} 
0

請使用以下的ValueObject格式不解析第一個整數元素

public class ResponseVO { 
    public List<Response> response = new ArrayList(); 
    public class Response { 
     public final long id; 
     public final long from_id; 
     ... 
    } 
}