GSON结构困难

时间:2017-10-26 04:07:11

标签: java json gson

关于为我的JSON文件创建结构以轻松反序列化,我有点不确定。该文件是GitHub的圣经翻译。

现有代码:

JSONArray bibleData = new JSONArray(loadJSONFromAsset("KJV"));

bibleBooks = new JSONArray[66];
Integer[] bibleChapters = new Integer[66];

int maxChapters = 0;

for (int i = 0; i < BIBLE.length; i++) {

    bibleBooks[i]  = (JSONArray) bibleData.getJSONObject(i).get("chapters");
    bibleChapters[i] = bibleBooks[i].length();

    if (bibleChapters[i] > maxChapters) {

        maxChapters = bibleChapters[i];

    }

}
//Get individual chapters in JSON array

JSONObject[][] chapters = new JSONObject[BIBLE.length][maxChapters];

int iVal = 0;
int i1Val = 0;

try {

    for (int i = 0; i < BIBLE.length;i++) {

        iVal = i;

        for (int i1 = 0; i1 < maxChapters; i1++) {

            i1Val = i1;

            // Ensure don't start to access non-existent chapters
            if (i1 < bibleChapters[i]) {

                chapters[i][i1] = bibleBooks[i].getJSONObject(i1);


            } else {

                break;

            }

        }
    }
} catch (Exception e) {
    e.printStackTrace();
    Log.i("JSON Read Error","i = " + Integer.toString(iVal) + ", i1 = " + Integer.toString(i1Val));

}

它可以达到某种程度,但是在访问章节JSONArray并为每个项目创建一个对象后我陷入了困境。我无法弄清楚如何访问“1”(章节#)和随后的经文。

获取章节[0] [0]会返回正确的部分,但看起来像这样:

{"1":{"1":"In the beginning God created the heaven and the earth.","2":"And the.....

我尝试从中提取JSONObject,但是当我输入chapter [i] [i1] .get(“1”)或chapter [i] [i1] .get(0)时,它失败了。

GSON

我已经更新了我的GSON,但它返回以下内容:

GSON Output: [[[abbrev=gn, book=Genesis, chapters=[[null], [null], [null], [null], [null],

每本书都会显示正确数量的[null]章节,但是它们显然没有正确阅读,我不确定我做错了什么。此外,它只是我或应该只有“[[”在开头,而不是“[[[”???这是一系列书籍,而不是一系列书籍。

public class Book {
    private String abbrev;
    private String book;
    private List<Chapter> chapters;

    public String getAbbrev() {
        return abbrev;
    }

    public void setAbbrev(String abbrev) {
        this.abbrev = abbrev;
    }

    public String getBook() {
        return book;
    }

    public void setBook(String book) {
        this.book = book;
    }

    public List<Chapter> getChapters() {
        return chapters;
    }

    public void setChapters(List<Chapter> chapters) {
        this.chapters = chapters;
    }

    @Override
    public String toString() {
        return "[abbrev=" + abbrev + ", book=" + book + ", chapters=" + chapters + "]";
    }

}

/**
 * Chapter POJO
 */
public class Chapter {
    private List<Verses> verses;

    public List<Verses> getVerses() {
        return verses;
    }

    public void setVerses(List<Verses> verses) {
        this.verses = verses;
    }

    @Override
    public String toString() {
        return "[" + verses + "]";
    }

}

/**
 * Verse POJO
 */
public class Verses {
    private List<Verse> verse;

    public List<Verse> getVerse() {
        return verse;
    }

    public void setVerse(List<Verse> verse) {
        this.verse = verse;
    }

    @Override
    public String toString() {
        return "[" + verse + "]";
    }

}

public class Verse {

    private String verseNum;
    private String verseContent;

    public String getverseNum() {
        return verseNum;
    }

    public void setverseNum(String verseNum) {
        this.verseNum = verseNum;
    }

    public String verseContent() {
        return verseContent;
    }

    public void verseContent(String verseContent) {
        this.verseContent = verseContent;
    }

    @Override
    public String toString() {
        return "{"+ verseNum + ", " + verseContent + "}";
    }

}

1 个答案:

答案 0 :(得分:0)

GSON是一个非常强大的库,它可以轻松解决此类JSON反序列化问题。唯一的问题是,你需要有正确的POJO。

查看您的JSON结构,您似乎拥有ListBook个项目。因此,让我们开始创建合适的POJO。

第1步:创建一个名为Book的POJO类,其中包含abbrevbookchapters成员:

public class Book {
    private String abbrev;
    private String book;
    private List<Chapter> chapters;

    public String getAbbrev() {
        return abbrev;
    }

    public void setAbbrev(String abbrev) {
        this.abbrev = abbrev;
    }

    public String getBook() {
        return book;
    }

    public void setBook(String book) {
        this.book = book;
    }

    public List<Chapter> getChapters() {
        return chapters;
    }

    public void setChapters(List<Chapter> chapters) {
        this.chapters = chapters;
    }

    @Override
    public String toString() {
        return "Book [abbrev=" + abbrev + ", book=" + book + ", chapters=" + chapters + "]";
    }

}

第2步:创建一个名为Chapter的POJO类。仔细观察,每个Chapter都有3个Verse。所以你还需要一个Verse POJO类,它有2个String个成员。我们将其称为verseContent1verseContent2。因此,您的ChapterVerse类应如下所示:

/**
 * 
 * Chapter POJO
 *
 */
public class Chapter {
    @SerializedName("1")
    private Verse verse1;
    @SerializedName("2")
    private Verse verse2;
    @SerializedName("3")
    private Verse verse3;

    public Verse getVerse1() {
        return verse1;
    }

    public void setVerse1(Verse verse1) {
        this.verse1 = verse1;
    }

    public Verse getVerse2() {
        return verse2;
    }

    public void setVerse2(Verse verse2) {
        this.verse2 = verse2;
    }

    public Verse getVerse3() {
        return verse3;
    }

    public void setVerse3(Verse verse3) {
        this.verse3 = verse3;
    }

    @Override
    public String toString() {
        return "Chapter [verse1=" + verse1 + ", verse2=" + verse2 + ", verse3=" + verse3 + "]";
    }

}

/**
 * 
 * Verse POJO
 *
 */
public class Verse {
    @SerializedName("1")
    private String verseContent1;
    @SerializedName("2")
    private String verseContent2;

    public String getVerseContent1() {
        return verseContent1;
    }

    public void setVerseContent1(String verseContent1) {
        this.verseContent1 = verseContent1;
    }

    public String getVerseContent2() {
        return verseContent2;
    }

    public void setVerseContent2(String verseContent2) {
        this.verseContent2 = verseContent2;
    }

    @Override
    public String toString() {
        return "Verse [verseContent1=" + verseContent1 + ", verseContent2=" + verseContent2 + "]";
    }

}

现在,您的平台已设置完毕。您的下一个方法是使用这些POJO将您的JSON反序列化为List<Book>对象。

当您的JSON作为数组启动时,在您的客户端代码中,您需要创建一个TypeToken以在运行时获取封闭对象的信息。由于TypeToken在运行时使用反射,因此您可以将List<Book>的类型存储在java.lang.reflect.Type变量中。稍后您可以使用相同的方法来获取反序列化的对象。您的代码段应如下所示:

Gson gson = new GsonBuilder().setPrettyPrinting().create();

Type bookList = new TypeToken<List<Book>>(){}.getType();
//Get a List of Book
List<Book> bible = gson.fromJson(new FileReader(jsonFilePath), bookList);

稍后您可以迭代此List<Book>来执行特定操作。 我希望这有助于您的学习活动。