簡體   English   中英

將對象/數組從 JSON 解析為 Java

[英]Parsing Objects/Arrays from JSON to Java

我是 JSON 的新手,我正在嘗試將我的 JSON 文件解析為 Java,它可以工作,但我有包含更多數組的對象/數組,我不知道如何正確迭代它。 這是我的 JSON 文件:

{
    "quiz": {
        "sport": {
            "q1": {
                "question": "Which one is correct team name in NBA?",
                "options": [
                    "New York Bulls",
                    "Los Angeles Kings",
                    "Golden State Warriros",
                    "Huston Rocket"
                ],
                "answer": "Huston Rocket"
            }
        },
        "maths": {
            "q1": {
                "question": "5 + 7 = ?",
                "options": [
                    "10",
                    "11",
                    "12",
                    "13"
                ],
                "answer": "12"
            },
            "q2": {
                "question": "12 - 8 = ?",
                "options": [
                    "1",
                    "2",
                    "3",
                    "4"
                ],
                "answer": "4"
            }
        }
    }
}

我不知道如何獲取此結構中的所有數據。 我的意思是我知道這是一個測驗,兩個主題是運動和數學,每個主題都有問題和答案。

我希望每個值都可用。

這是我的 Java 代碼

JSONParser jsonParser = new JSONParser();

        try
        {

                JSONArray a = (JSONArray) jsonParser.parse("pathToFile");
                for (Object o : a)
                {
                    JSONObject task1 = (JSONObject) o;
                    String name = (String) task1.get("quiz");
                    System.out.println(name);

                    String topic = (String) task1.get("sport");
                    System.out.println(topic);

                }

        }catch (ParseException e)
        {
            e.printStackTrace();
        }
       catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

有人可以向我解釋邏輯嗎?

首先,您需要創建類,比較對象更容易

此鏈接可以幫助您將 json 轉換為類

https://www.site24x7.com/tools/json-to-java.html

它們是生成的類

/* * 要更改此許可證標題,請在項目屬性中選擇許可證標題。 * 要更改此模板文件,請選擇工具 | 模板 * 並在編輯器中打開模板。 */ 包 com.examen.overflow;

/**
 *
 * @author wilso
 */
public class Dto {

    private Quiz quiz;

    public Quiz getQuiz() {
        return quiz;
    }

    public void setQuiz(Quiz quiz) {
        this.quiz = quiz;
    }
}


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.examen.overflow;

/**
 *
 * @author wilso
 */
public class Maths {

    private Question q1;
    private Question q2;

    // Getter Methods 
    public Question getQ1() {
        return q1;
    }

    public Question getQ2() {
        return q2;
    }

    // Setter Methods 
    public void setQ1(Question q1) {
        this.q1 = q1;
    }

    public void setQ2(Question q2) {
        this.q2 = q2;
    }
}


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.examen.overflow;

import java.util.List;

/**
 *
 * @author wilso
 */
public class Question {

    private String answer;
    private List<String> options;
    private String question;

    public String getAnswer() {
        return answer;
    }

    public void setAnswer(String answer) {
        this.answer = answer;
    }

    public List<String> getOptions() {
        return options;
    }

    public void setOptions(List<String> options) {
        this.options = options;
    }

    public String getQuestion() {
        return question;
    }

    public void setQuestion(String question) {
        this.question = question;
    }

}


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.examen.overflow;

/**
 *
 * @author wilso
 */
public class Quiz {

    private Sport sport;
    private Maths maths;

    public Sport getSportObject() {
        return sport;
    }

    public void setSportObject(Sport sport) {
        this.sport = sport;
    }

    public Maths getMathsObject() {
        return maths;
    }

    public void setMathsObject(Maths maths) {
        this.maths = maths;
    }

}


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.examen.overflow;

/**
 *
 * @author wilso
 */
public class Sport {

    Question q1;

    // Getter Methods 
    public Question getQ1() {
        return q1;
    }

    // Setter Methods 
    public void setQ1(Question question) {
        this.q1 = question;
    }
}

當你有課時,你只需要做下一個

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.examen.overflow;

import com.google.gson.Gson;

public class Convert {

    public static void main(String[] args) {
        String json = "{\n"
                + "    \"quiz\": {\n"
                + "        \"sport\": {\n"
                + "            \"q1\": {\n"
                + "                \"question\": \"Which one is correct team name in NBA?\",\n"
                + "                \"options\": [\n"
                + "                    \"New York Bulls\",\n"
                + "                    \"Los Angeles Kings\",\n"
                + "                    \"Golden State Warriros\",\n"
                + "                    \"Huston Rocket\"\n"
                + "                ],\n"
                + "                \"answer\": \"Huston Rocket\"\n"
                + "            }\n"
                + "        },\n"
                + "        \"maths\": {\n"
                + "            \"q1\": {\n"
                + "                \"question\": \"5 + 7 = ?\",\n"
                + "                \"options\": [\n"
                + "                    \"10\",\n"
                + "                    \"11\",\n"
                + "                    \"12\",\n"
                + "                    \"13\"\n"
                + "                ],\n"
                + "                \"answer\": \"12\"\n"
                + "            },\n"
                + "            \"q2\": {\n"
                + "                \"question\": \"12 - 8 = ?\",\n"
                + "                \"options\": [\n"
                + "                    \"1\",\n"
                + "                    \"2\",\n"
                + "                    \"3\",\n"
                + "                    \"4\"\n"
                + "                ],\n"
                + "                \"answer\": \"4\"\n"
                + "            }\n"
                + "        }\n"
                + "    }\n"
                + "}";
        Dto quiz = new Gson().fromJson(json, Dto.class);
        System.out.println(quiz);
        //Iterate object
        for (String option : quiz.getQuiz().getMathsObject().getQ1().getOptions()) {
            System.out.println(option);
        }
    }
}

假設您不想使用 GSON 並在處理測驗對象時放任自己的邏輯:
分析 JSON 並為值創建邏輯對象。 然后,當您讀取 JSON 時,您可以根據需要創建對象並根據需要附加它們。

您需要測驗、類別、問題和選​​項對象。

那么你的代碼會變成這樣(偽代碼,沒有測試它是否真的有效):

 public Quiz createQuiz(JSONObject raw) 
 {
     Quiz quiz = new Quiz();

     Iterator<String> keys = raw.keys();
     while(keys.hasNext()) {
        String key = keys.next();
        if (raw.get(key) instanceof JSONObject) { 
           JSONObject rawCategory = (JSONObject)raw.get(key);
           quiz.addCategory(this.createCategory(key, rawCategory));
        }
    } 
    return quiz;
}
public Category createCategory(String name, JSONObject raw) 
{
    Category category = new Category(name);
    Iterator<String> keys = raw.keys();
     while(keys.hasNext()) {
        String key = keys.next();
        if (raw.get(key) instanceof JSONObject) { 
           JSONObject rawQuestion = (JSONObject)raw.get(key);
           category.addQuestion(this.createQuestion(key, rawQuestion));
        }
    } 
   return category;
}

public Category createQuestion(String name, JSONObject raw) 
{
    Question question = new Question(name);
    if(raw.hasKey("question") && raw.get("question") instanceof String) {
       question.setQuestionText((String) raw.get("question"));
    }
    if(raw.hasKey("answer") && raw.get("answer") instanceof String) {
       question.setAnswerText((String) raw.get("answer"));
    }
    if(raw.hasKey("options") && raw.get("options") instanceof JSONArray) {
       JSONArray rawOptions = (JSONArray)raw.get("options");
       for(Object rawOption : rawOptions) {
          if(rawOption instanceof String) {
             question.addOption(this.createOption((String) rawOption));
          } 
       }
    }
   return question;
}

暫無
暫無

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

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