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条)

报告相同问题?

悬赏问题

  • ¥15 想用@vueuse 把项目动态改成深色主题,localStorge里面的vueuse-color-scheme一开始就给我改成了dark,不知道什么原因(相关搜索:背景颜色)
  • ¥20 OPENVPN连接问题
  • ¥15 flask实现搜索框访问数据库
  • ¥15 mrk3399刷完安卓11后投屏调试只能显示一个设备
  • ¥20 白日门传奇少一个启动区服和启动服务器的快捷键,东西都是全的 , 他们说套一个出来就行了 但我就是弄不好,谁看看,
  • ¥100 如何用js写一个游戏云存档
  • ¥15 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题
  • ¥15 需要写计算过程,不要写代码,求解答,数据都在图上
  • ¥15 向数据表用newid方式插入GUID问题