dongmu2026 2016-04-29 20:58 采纳率: 100%
浏览 16
已采纳

我无法制作这个JSON

I'm currently making a mcq for a medical application and i want to make a Json from my database by a php but it's isn't working, someone advice me to Having a JSONObject for the question and a JSONArray for the Choices but i'm not able to make this and i don't understand why ! I followed a lot a tutorial but i can't figure out why i can't make this JSON :

{ //This is the JSON i want to make !
    "QCM": {
        "question": "Est-ce que Captain America gagne contre IronMan",
        "id": "31",
        "choix": ["Oui", "Non"]
    }
}

But i can't, currently my PHP code is :

$db = mysqli_connect($host,$user,$pass,$db);


$questions = $db->query("SELECT question, id FROM question ORDER BY rand() LIMIT 1");
while($row = mysqli_fetch_assoc($questions)){
    $id=$row['id'];
    $QCM[] = $row;

$choix = $db->query("SELECT choix FROM choix WHERE id_question = $id ORDER BY rand()");

while ($row = mysqli_fetch_assoc($choix)) {
    $QCM[] = $row;

    }
}
echo json_encode(array("QCM"=>$QCM));

and there is the JSON i can get with this code :

{ //I don't want this JSON because i can't read the "choix" in my application
    "QCM": [{
        "question": "Est-ce que Batman gagne contre Superman",
        "id": "30"
    }, {
        "choix": "Oui"
    }, {
        "choix": "Non"
    }]
}

I hope someone can help me because i can't make the right json !

Here is my JAVA :

try
                        {
                            JSONArray QCM = response.getJSONArray("QCM");
                            for (int i=0; i<QCM.length(); i++) {
                                JSONObject getQcmObject = QCM.getJSONObject(i);
                                String questionGet = getQcmObject.getString("question");
                                symptomesQuestions.setText(questionGet);

                                JSONArray CHOIX = response.getJSONArray("choix");
                                for (int x =0; x<CHOIX.length(); x++){
                                    JSONObject getChoixObject = CHOIX.getJSONObject(x);
                                    String choiceGet = getChoixObject.getString("choix")
                                    lesChoixButton.setText(choiceGet);
                                }
                            }

PHP structure required to create the example JSON

$jsonPhp = 
    (object) (array(
       'QCM' => 
           (object) (array(
                 'question' => 'Est-ce que Captain America gagne contre IronMan',
                 'id' => '31',
                 'choix' => 
            array (
                  0 => 'Oui',
                  1 => 'Non',
            ),
      )),
    ));

Online tool to compare JSON structures for differences...

As print_r:

stdClass Object
(
    [QCM] => stdClass Object
        (
            [question] => Est-ce que Captain America gagne contre IronMan
            [id] => 31
            [choix] => Array
                (
                    [0] => Oui
                    [1] => Non
                )
        )
)
  • 写回答

2条回答 默认 最新

  • doubi4435 2016-04-29 21:25
    关注

    Did you try something like this:

    <?php
    
    $db         = mysqli_connect($host,$user,$pass,$db);
    $counter    = 0;
    $questions  = $db->query("SELECT question, id FROM question ORDER BY rand() LIMIT 1");
    while($row  = mysqli_fetch_assoc($questions)){
        $id     = $row['id'];
        $QCM[]  = $row;
    
        $choix  = $db->query("SELECT choix FROM choix WHERE id_question = $id ORDER BY rand()");
    
        $arrTemp= array();      // HERE A TEMPORAL ARRAY 
        while ($row2 = mysqli_fetch_assoc($choix)) {
            $arrTemp[] = $row2['choix'];
        }
        //TRY THIS:
        $QCM[$counter]["choix"]  = $arrTemp; //ADD THE TEMPORAL ARRAY TO THE $QCM ARRAY
        $counter++;
    }
    echo json_encode(array("QCM"=>$QCM));
    

    I suggest you try this in your Java Code:

    package com.company;
    
    import org.json.JSONArray;
    import org.json.JSONObject;
    
    
    public class Main {
    
    public static void main(String[] args) {
        String jsonExample      = "[{\"QCM\":{\"question\":\"Est-ce que Captain America gagne contre IronMan\",\"id\":\"31\",\"choix\":[\"Oui\",\"Non\"]}}, {\"QCM\":{\"question\":\"Do you know who the 1st President of the United States is?\",\"id\":\"32\",\"choix\":[\"Yes\",\"No\"]}}]";
        JSONArray jsonArray;
        try{
            jsonArray           = new JSONArray(jsonExample);
    
            for(int i = 0; i<jsonArray.length(); i++){
                JSONObject tempObject   = jsonArray.getJSONObject(i);
                JSONObject qcmObject    = tempObject.getJSONObject("QCM");
                String qcmQuestion      = qcmObject.getString("question");
                JSONArray qcmChoice     = qcmObject.getJSONArray("choix");
                //SET THE TEXT IN THE TEXT FIELD:
                ////symptomesQuestions.setText(qcmQuestion);
    
                //NOW LOOP THROUGH THE ARRAY OF CHOICES AND DO AS YOU WISH WITH THE CONTENT...
                for(int c=0; c<qcmChoice.length(); c++){
                    //BECAUSE YOU MAY HAVE MORE THAN 1 CHOICES, YOU MAY HAVE TO CREATE YOUR BUTTONS DYNAMICALLY...
                    //IF YOU SET THE BUTTON TEXT OF lesChoixButton TO ANY VALUE, SUBSEQUENT VALUES IN THE LOOP WILL OVERRIDE IT.
                    //SO DYNAMICALLY CREATE YOUR BUTTONS....
                    System.out.println( qcmChoice.get(c) + "
    ");   // PRINTS Oui   Non...  AND THEN Yes    No  
                    ////lesChoixButton.setText(qcmChoice.get(c));
                }
    
                System.out.print(qcmQuestion);
                System.out.print("
    
    ");
                System.out.print(qcmChoice);
                System.out.print("
    
    ");
    
            }
        }catch (Exception e){
    
        }
    }
    }
    

    Test this Code:

    package com.company;
    
        import org.json.JSONArray;
        import org.json.JSONObject;
    
        import javax.swing.*;
        import java.awt.*;
    
    
        public class Main extends JFrame{
    
            Main(String g){
                super(g);     
            }
    
            public static void main(String[] args) {
                String jsonExample      = "[{\"QCM\":{\"question\":\"Est-ce que Captain America gagne contre IronMan\",\"id\":\"31\",\"choix\":[\"Oui\",\"Non\"]}}, {\"QCM\":{\"question\":\"Do you know who the 1st President of the United States is?\",\"id\":\"32\",\"choix\":[\"Yes\",\"No\"]}}]";
                JSONArray jsonArray;
                try{
                    jsonArray           = new JSONArray(jsonExample);
                    Main fr             = new Main("QCM QUESTIONS");
                    fr.setLayout(new GridLayout(10,10));
                    final JPanel  tempPanel     = new JPanel();
                    tempPanel.setLayout(new GridLayout(4,4));
    
                    for(int i = 0; i<jsonArray.length(); i++){
                        JSONObject tempObject   = jsonArray.getJSONObject(i);
                        JSONObject qcmObject    = tempObject.getJSONObject("QCM");
                        String qcmQuestion      = qcmObject.getString("question");
                        JSONArray qcmChoice     = qcmObject.getJSONArray("choix");
                        JTextField  tempQuest   = new JTextField(20);
                        tempQuest.setText(qcmQuestion);
                        fr.add(tempQuest);
    
                        //SET THE TEXT IN THE TEXT FIELD:
                        ////symptomesQuestions.setText(qcmQuestion);
    
                        //NOW LOOP THROUGH THE ARRAY OF CHOICES AND DO AS YOU WISH WITH THE CONTENT...
                        for(int c=0; c<qcmChoice.length(); c++){
                            //BECAUSE YOU MAY HAVE MORE THAN 1 CHOICES, YOU MAY HAVE TO CREATE YOUR BUTTONS DYNAMICALLY...
                            //IF YOU SET THE BUTTON TEXT OF lesChoixButton TO ANY VALUE, SUBSEQUENT VALUES IN THE LOOP WILL OVERRIDE IT.
                            //SO DYNAMICALLY CREATE YOUR BUTTONS....
                            System.out.println( qcmChoice.get(c) + "
    ");   // PRINTS Oui   Non...  AND THEN Yes    No
                            final JButton  tempBtn     = new JButton();
                            tempBtn.setAlignmentX(0);
                            tempBtn.setAlignmentY(20 + 20*c);
                            tempBtn.setSize(new Dimension(150, 30));
    
                            tempBtn.setText( (String)qcmChoice.get(c) );
                            fr.add(tempBtn);
                           //fr.add(tempBtn);
                            ////lesChoixButton.setText(qcmChoice.get(c));
                        }
                        final JLabel tempSpacer     = new JLabel( " " );
                        tempSpacer.setText( "  ");
                        fr.add(tempSpacer);
    
                        System.out.print(qcmQuestion);
                        System.out.print("
    
    ");
                        System.out.print(qcmChoice);
                        System.out.print("
    
    ");
    
                    }
    
                    fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    fr.setVisible(true);
                    fr.setSize(300,300);
                }catch (Exception e){
    
                }
            }
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系