簡體   English   中英

Gson:獲取嵌套在 object 中的對象數組,而 object 又嵌套在整個 JSON26668CFDE63131BC4BEB668CFDE63131BC4BEB66

[英]Gson: Get an array of objects which is nested in an object, which in turn is nested in an entire JSON object

編輯

我很想聽聽任何解決方案。 它不必與 Gson 一起使用。 另外,如果您知道有關解析嵌套 JSON 的好教程,如果您能告訴我它的名稱或提供鏈接,我會很高興。

需要多少張SQLite表? 截至目前,我有一張桌子。 每個嵌套的 object 都需要一個表嗎?

原來的問題

我正在嘗試使用 Gson 獲取這個嵌套的對象數組。 我嘗試使用 TypeToken,但找不到關於如何實現 TypeToken 的規則(這些規則可能有助於將 TypeToken 用於特定的 JSON)。

JSON

{
  "_embedded": {
    "episodes":[
      {
        "name": "Probe",
        "summary": "adasdasdas"
      },
      {...},
      {...}
      ]
   }
}

我嘗試了什么

// inserting the JSON to SQLite
    private void insertToSQLite(SQLiteDatabase db) {

        Gson gson = new Gson();
        Type listType = new TypeToken<List<Episode>>(){}.getType();
        List<Episode> episodesList = gson.fromJson(output, listType);

        for(Episode episode : episodesList) {

            ContentValues insertValues = new ContentValues();

            insertValues.put(Episode.ID, episode.getId());
            insertValues.put(Episode.TITLE, episode.getTitle());
            insertValues.put(Episode.SUMMARY, episode.getSummary());
...
        }
    }

謝謝。

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import com.google.common.reflect.TypeParameter;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

public class TestJson {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
    Gson gson = new Gson();
    String jsonString = "{\"_embedded\": { \"episodes\":[{\"name\": \"Probe\",\"summary\": \"adasdasdas\" }]}}";
    JsonElement jsonObject = new JsonParser().parse(jsonString).getAsJsonObject().get("_embedded").getAsJsonObject()
            .get("episodes");
    Type listType = setModelAndGetCorrespondingList(Episode.class);
    List<Episode> episodes = gson.fromJson(jsonObject, listType);

    System.out.println(episodes);
}

private static <T> Type setModelAndGetCorrespondingList(Class<T> type) {
    return new TypeToken<ArrayList<T>>() {
    }.where(new TypeParameter<T>() {
    }, type).getType();
}

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM