如何将每行检索为json对象

时间:2015-02-23 05:34:38

标签: php android mysql

我的PHP代码是这样的:

<?php
$host="localhost"; //replace with database hostname 
$username="root"; //replace with database username 
$password=""; //replace with database password 
$db_name="hg"; //replace with database name

$con=mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");
$sql = "select * from tblquestion"; 
$result = mysql_query($sql);
$json = array();

if(mysql_num_rows($result)){
while($row=mysql_fetch_assoc($result)){
$json['emp_info'][]=$row;
}
}
mysql_close($con);
echo json_encode($json); 
?> 

我的输出是:

    {
    "emp_info": [
        {
            "QuestionId": "1",
            "Question": "Had dinner?",
            "TeacherId": "2",
            "GradeId": "1",
            "SectionId": "",
            "SubjectId": "1",
            "NofOption": "2",
            "COptionId": "1",
            "Score": "5",
            "isupdated": "0"
        },
        {
            "QuestionId": "2",
            "Question": "Give two examples to illustrate Newton’s second law of motion.",
            "TeacherId": "11",
            "GradeId": "6",
            "SectionId": "",
            "SubjectId": "48",
            "NofOption": "0",
            "COptionId": "0",
            "Score": "3",
            "isupdated": "0"
        },
        {
            "QuestionId": "3",
            "Question": "Question.1: Define ‘Balanced’ and ‘Unbalanced’ forces. Illustrate with examples.",
            "TeacherId": "11",
            "GradeId": "0",
            "SectionId": "",
            "SubjectId": "0",
            "NofOption": "0",
            "COptionId": "0",
            "Score": "5",
            "isupdated": "0"
        },
        {
            "QuestionId": "4",
            "Question": "Question.2: What is inertia? How many types of inertia are there?",
            "TeacherId": "11",
            "GradeId": "6",
            "SectionId": "",
            "SubjectId": "48",
            "NofOption": "0",
            "COptionId": "0",
            "Score": "3",
            "isupdated": "0"
        },
        {
            "QuestionId": "5",
            "Question": "Question.3: Define: (a) Momentum, (b) Newton",
            "TeacherId": "11",
            "GradeId": "6",
            "SectionId": "",
            "SubjectId": "48",
            "NofOption": "0",
            "COptionId": "0",
            "Score": "3",
            "isupdated": "0"
        },
        {
            "QuestionId": "6",
            "Question": "Question.4: State the various effects of force. So",
            "TeacherId": "11",
            "GradeId": "6",
            "SectionId": "",
            "SubjectId": "48",
            "NofOption": "0",
            "COptionId": "0",
            "Score": "3",
            "isupdated": "0"
        },
        {
            "QuestionId": "7",
            "Question": "Question.5: State Newton’s first law of motion. Why the Newton’s first law of motion is also called ‘Law of Inertia’?",
            "TeacherId": "11",
            "GradeId": "6",
            "SectionId": "",
            "SubjectId": "48",
            "NofOption": "0",
            "COptionId": "0",
            "Score": "4",
            "isupdated": "0"
        },
        {
            "QuestionId": "8",
            "Question": "Question.6: What is the relation between mass and inertia?",
            "TeacherId": "11",
            "GradeId": "6",
            "SectionId": "",
            "SubjectId": "48",
            "NofOption": "0",
            "COptionId": "0",
            "Score": "3",
            "isupdated": "0"
        },
        {
            "QuestionId": "9",
            "Question": "Question.7: State and explain Newton’s second law of motion.",
            "TeacherId": "11",
            "GradeId": "6",
            "SectionId": "",
            "SubjectId": "48",
            "NofOption": "0",
            "COptionId": "0",
            "Score": "3",
            "isupdated": "0"
        },
        {
            "QuestionId": "10",
            "Question": "Question.9: Explain how Newton’s second law of motion can be used to derive a quantitative definition of Force.",
            "TeacherId": "11",
            "GradeId": "6",
            "SectionId": "",
            "SubjectId": "48",
            "NofOption": "0",
            "COptionId": "0",
            "Score": "4",
            "isupdated": "0"
        },
        {
            "QuestionId": "11",
            "Question": "State Law of Conservation of Momentum. Deduce this from Newton’s second law of motion.",
            "TeacherId": "11",
            "GradeId": "6",
            "SectionId": "",
            "SubjectId": "48",
            "NofOption": "0",
            "COptionId": "0",
            "Score": "4",
            "isupdated": "0"
        },
        {
            "QuestionId": "12",
            "Question": "who is captain of indian cricket team?",
            "TeacherId": "3",
            "GradeId": "1",
            "SectionId": "",
            "SubjectId": "1",
            "NofOption": "2",
            "COptionId": "1",
            "Score": "1",
            "isupdated": "0"
        },
        {
            "QuestionId": "13",
            "Question": "what is your name?",
            "TeacherId": "352",
            "GradeId": "8",
            "SectionId": "",
            "SubjectId": "121",
            "NofOption": "3",
            "COptionId": "1",
            "Score": "10",
            "isupdated": "1"
        },
        {
            "QuestionId": "14",
            "Question": "in which school?",
            "TeacherId": "352",
            "GradeId": "8",
            "SectionId": "",
            "SubjectId": "121",
            "NofOption": "4",
            "COptionId": "3",
            "Score": "10",
            "isupdated": "1"
        },
        {
            "QuestionId": "15",
            "Question": "name",
            "TeacherId": "352",
            "GradeId": "9",
            "SectionId": "",
            "SubjectId": "0",
            "NofOption": "3",
            "COptionId": "1",
            "Score": "1",
            "isupdated": "1"


       },
        {
            "QuestionId": "16",
            "Question": "meeting",
            "TeacherId": "352",
            "GradeId": "9",
            "SectionId": "",
            "SubjectId": "0",
            "NofOption": "4",
            "COptionId": "3",

        "Score": "1",
            "isupdated": "1"
        },
        {
            "QuestionId": "17",
            "Question": "do u want to go home?",
            "TeacherId": "2",
            "GradeId": "1",
            "SectionId": "",
            "SubjectId": "1",
            "NofOption": "2",
            "COptionId": "2",
            "Score": "1",
            "isupdated": "0"
        }
    ]
}

现在我想在android中单独检索每个questionId(即question,teacherId,grade等)数据。 例如: questionId:1,问题:吃过饭,老师ID:2 ... questionId:2,问题:举两个例子,老师ID:11 ... questionId:3,问题:定义,teacherId:11 ...

2 个答案:

答案 0 :(得分:1)

通常使用像GSON这样的库来处理这种情况。

GSON可以将json对象映射到自定义助手类中。

让我们首先创建一个辅助类,它将与json字符串一起映射.notice类的属性必须与json完全匹配。创建一个名为EmpInfoHelper的新Java文件:

public class EmInfoHelper {


private String QuestionId;
private String Question;
private String TeacherId;
private String GradeId;
private String SectionId;
private String SubjectId;
private String NofOption;
private String COptionId;
private String Score;
private String isupdated;

public EmInfoHelper() {
}

public String getQuestionId() {
    return QuestionId;
}

public void setQuestionId(String questionId) {
    QuestionId = questionId;
}

public String getQuestion() {
    return Question;
}

public void setQuestion(String question) {
    Question = question;
}

public String getTeacherId() {
    return TeacherId;
}

public void setTeacherId(String TeacherId) {
    this.teacherId = TeacherId;
}

public String getGradeId() {
    return GradeId;
}

public void setGradeId(String gradeId) {
    GradeId = gradeId;
}

public String getSectionId() {
    return SectionId;
}

public void setSectionId(String sectionId) {
    SectionId = sectionId;
}

public String getSubjectId() {
    return SubjectId;
}

public void setSubjectId(String subjectId) {
    SubjectId = subjectId;
}

public String getNofOption() {
    return NofOption;
}

public void setNofOption(String nofOption) {
    NofOption = nofOption;
}

public String getCOptionId() {
    return COptionId;
}

public void setCOptionId(String COptionId) {
    this.COptionId = COptionId;
}

public String getScore() {
    return Score;
}

public void setScore(String score) {
    Score = score;
}

public String getIsupdated() {
    return isupdated;
}

public void setIsupdated(String isupdated) {
    this.isupdated = isupdated;
}
}

然后你像这样检索JSON:

注意 在异步任务中异步执行此操作是一种很好的做法。如果您需要有关异步的帮助,请询问。

    String reply;

    String url = "http://10.0.0.17/yourfilename.php"; //Enter your url here

    BufferedReader inStream = null;
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpRequest = new HttpGet(url);

    try {
        HttpResponse response = httpClient.execute(httpRequest);
        inStream = new BufferedReader(
                new InputStreamReader(
                        response.getEntity().getContent()));

        StringBuffer buffer = new StringBuffer("");
        String line = "";

        while ((line = inStream.readLine()) != null) {
            buffer.append(line);
        }
        inStream.close();

        reply = buffer.toString();

        //If we have a reply process Json

        if(reply != null && reply.length() > 0)
        {

            JSONArray array = null;

            try {
                JSONObject jsonResp = new JSONObject(reply);
                array = jsonResp.getJSONArray("emp_info");

            } catch (JSONException e) {
                e.printStackTrace();
                return;
            }

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

                JSONObject jsonObj = null;
                try {
                    jsonObj = (JSONObject) array.get(i);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                Gson gson = new Gson();
                EmpInfoHelper emp = gson.fromJson(jsonObj.toString(), EmpInfoHelper.class);

                //Here We have an object ..do what ever you like
                Log.d("DATA", emp.getQuestion());

            }

        }

    } catch (Exception e) {

    }

<强>更新

要在Android Studio中使用GSON,因为没有Graven,您必须手动将库添加到项目中。首先从here下载jar文件,下载gson-2.3.1.jar

enter image description here

在你的app目录中创建一个名为libs的文件夹并将库粘贴到那里。

enter image description here

然后在Android Studio中右键单击应用程序目录并选择打开“模块设置”:

enter image description here

然后依赖选项卡和底部的+新文件:

enter image description here

enter image description here

选择GSON

enter image description here

在项目树中..选择buil.gradle(模块:app)

enter image description here

在依赖项下添加以下内容:

enter image description here

我相信你很高兴。

答案 1 :(得分:0)

Try this..

    <?php
    $test='{"emp_info":[{"QuestionId":"1","Question":"Had dinner?","TeacherId":"2","GradeId":"1","SectionId":"","SubjectId":"1","NofOption":"2","COptionId":"1","Score":"5","isupdated":"0"},{"QuestionId":"2","Question":"Give two examples to illustrate Newton\u2019s second law of motion.","TeacherId":"11","GradeId":"6","SectionId":"","SubjectId":"48","NofOption":"0","COptionId":"0","Score":"3","isupdated":"0"},{"QuestionId":"3","Question":"Question.1: Define \u2018Balanced\u2019 and \u2018Unbalanced\u2019 forces. Illustrate with examples.","TeacherId":"11","GradeId":"0","SectionId":"","SubjectId":"0","NofOption":"0","COptionId":"0","Score":"5","isupdated":"0"},{"QuestionId":"4","Question":"Question.2: What is inertia? How many types of inertia are there?","TeacherId":"11","GradeId":"6","SectionId":"","SubjectId":"48","NofOption":"0","COptionId":"0","Score":"3","isupdated":"0"},{"QuestionId":"5","Question":"Question.3: Define: (a) Momentum, (b) Newton","TeacherId":"11","GradeId":"6","SectionId":"","SubjectId":"48","NofOption":"0","COptionId":"0","Score":"3","isupdated":"0"},{"QuestionId":"6","Question":"Question.4: State the various effects of force. So","TeacherId":"11","GradeId":"6","SectionId":"","SubjectId":"48","NofOption":"0","COptionId":"0","Score":"3","isupdated":"0"},{"QuestionId":"7","Question":"Question.5: State Newton\u2019s first law of motion. Why the Newton\u2019s first law of motion is also called \u2018Law of Inertia\u2019?","TeacherId":"11","GradeId":"6","SectionId":"","SubjectId":"48","NofOption":"0","COptionId":"0","Score":"4","isupdated":"0"},{"QuestionId":"8","Question":"Question.6: What is the relation between mass and inertia?","TeacherId":"11","GradeId":"6","SectionId":"","SubjectId":"48","NofOption":"0","COptionId":"0","Score":"3","isupdated":"0"},{"QuestionId":"9","Question":"Question.7: State and explain Newton\u2019s second law of motion.","TeacherId":"11","GradeId":"6","SectionId":"","SubjectId":"48","NofOption":"0","COptionId":"0","Score":"3","isupdated":"0"},{"QuestionId":"10","Question":"Question.9: Explain how Newton\u2019s second law of motion can be used to derive a quantitative definition of Force.","TeacherId":"11","GradeId":"6","SectionId":"","SubjectId":"48","NofOption":"0","COptionId":"0","Score":"4","isupdated":"0"},{"QuestionId":"11","Question":"State Law of Conservation of Momentum. Deduce this from Newton\u2019s second law of motion.","TeacherId":"11","GradeId":"6","SectionId":"","SubjectId":"48","NofOption":"0","COptionId":"0","Score":"4","isupdated":"0"},{"QuestionId":"12","Question":"who is captain of indian cricket team?","TeacherId":"3","GradeId":"1","SectionId":"","SubjectId":"1","NofOption":"2","COptionId":"1","Score":"1","isupdated":"0"},{"QuestionId":"13","Question":"what is your name?","TeacherId":"352","GradeId":"8","SectionId":"","SubjectId":"121","NofOption":"3","COptionId":"1","Score":"10","isupdated":"1"},{"QuestionId":"14","Question":"in which school?","TeacherId":"352","GradeId":"8","SectionId":"","SubjectId":"121","NofOption":"4","COptionId":"3","Score":"10","isupdated":"1"},{"QuestionId":"15","Question":"name","TeacherId":"352","GradeId":"9","SectionId":"","SubjectId":"0","NofOption":"3","COptionId":"1","Score":"1","isupdated":"1"},{"QuestionId":"16","Question":"meeting","TeacherId":"352","GradeId":"9","SectionId":"","SubjectId":"0","NofOption":"4","COptionId":"3","Score":"1","isupdated":"1"},{"QuestionId":"17","Question":"do u want to go home?","TeacherId":"2","GradeId":"1","SectionId":"","SubjectId":"1","NofOption":"2","COptionId":"2","Score":"1","isupdated":"0"}]}';
   $testarray=json_decode($test,true);

$adata=array();
$data=array();
for($i=0;$i<count($testarray['emp_info']);$i++)
{
$adata['emp_info']=$testarray['emp_info'][$i];
$data[]=$adata;
echo '<pre>';
}
echo json_encode($data);
    ?>
**Output:**



[{"emp_info":{"QuestionId":"1","Question":"Had dinner?","TeacherId":"2","GradeId":"1","SectionId":"","SubjectId":"1","NofOption":"2","COptionId":"1","Score":"5","isupdated":"0"}},
 {"emp_info":{"QuestionId":"2","Question":"Give two examples to illustrate Newton\u2019s second law of motion.","TeacherId":"11","GradeId":"6","SectionId":"","SubjectId":"48","NofOption":"0","COptionId":"0","Score":"3","isupdated":"0"}},
{"emp_info":{"QuestionId":"3","Question":"Question.1: Define \u2018Balanced\u2019 and \u2018Unbalanced\u2019 forces. Illustrate with examples.","TeacherId":"11","GradeId":"0","SectionId":"","SubjectId":"0","NofOption":"0","COptionId":"0","Score":"5","isupdated":"0"}},
    {"emp_info":{"QuestionId":"4","Question":"Question.2: What is inertia? How many types of inertia are there?","TeacherId":"11","GradeId":"6","SectionId":"","SubjectId":"48","NofOption":"0","COptionId":"0","Score":"3","isupdated":"0"}},
    {"emp_info":{"QuestionId":"5","Question":"Question.3: Define: (a) Momentum, (b) Newton","TeacherId":"11","GradeId":"6","SectionId":"","SubjectId":"48","NofOption":"0","COptionId":"0","Score":"3","isupdated":"0"}},
    {"emp_info":{"QuestionId":"6","Question":"Question.4: State the various effects of force. So","TeacherId":"11","GradeId":"6","SectionId":"","SubjectId":"48","NofOption":"0","COptionId":"0","Score":"3","isupdated":"0"}},
    {"emp_info":{"QuestionId":"7","Question":"Question.5: State Newton\u2019s first law of motion. Why the Newton\u2019s first law of motion is also called \u2018Law of Inertia\u2019?","TeacherId":"11","GradeId":"6","SectionId":"","SubjectId":"48","NofOption":"0","COptionId":"0","Score":"4","isupdated":"0"}},
    {"emp_info":{"QuestionId":"8","Question":"Question.6: What is the relation between mass and inertia?","TeacherId":"11","GradeId":"6","SectionId":"","SubjectId":"48","NofOption":"0","COptionId":"0","Score":"3","isupdated":"0"}},
    {"emp_info":{"QuestionId":"9","Question":"Question.7: State and explain Newton\u2019s second law of motion.","TeacherId":"11","GradeId":"6","SectionId":"","SubjectId":"48","NofOption":"0","COptionId":"0","Score":"3","isupdated":"0"}},
    {"emp_info":{"QuestionId":"10","Question":"Question.9: Explain how Newton\u2019s second law of motion can be used to derive a quantitative definition of Force.","TeacherId":"11","GradeId":"6","SectionId":"","SubjectId":"48","NofOption":"0","COptionId":"0","Score":"4","isupdated":"0"}},
    {"emp_info":{"QuestionId":"11","Question":"State Law of Conservation of Momentum. Deduce this from Newton\u2019s second law of motion.","TeacherId":"11","GradeId":"6","SectionId":"","SubjectId":"48","NofOption":"0","COptionId":"0","Score":"4","isupdated":"0"}},
    {"emp_info":{"QuestionId":"12","Question":"who is captain of indian cricket team?","TeacherId":"3","GradeId":"1","SectionId":"","SubjectId":"1","NofOption":"2","COptionId":"1","Score":"1","isupdated":"0"}},
    {"emp_info":{"QuestionId":"13","Question":"what is your name?","TeacherId":"352","GradeId":"8","SectionId":"","SubjectId":"121","NofOption":"3","COptionId":"1","Score":"10","isupdated":"1"}},
    {"emp_info":{"QuestionId":"14","Question":"in which school?","TeacherId":"352","GradeId":"8","SectionId":"","SubjectId":"121","NofOption":"4","COptionId":"3","Score":"10","isupdated":"1"}},
    {"emp_info":{"QuestionId":"15","Question":"name","TeacherId":"352","GradeId":"9","SectionId":"","SubjectId":"0","NofOption":"3","COptionId":"1","Score":"1","isupdated":"1"}},
    {"emp_info":{"QuestionId":"16","Question":"meeting","TeacherId":"352","GradeId":"9","SectionId":"","SubjectId":"0","NofOption":"4","COptionId":"3","Score":"1","isupdated":"1"}},
    {"emp_info":{"QuestionId":"17","Question":"do u want to go home?","TeacherId":"2","GradeId":"1","SectionId":"","SubjectId":"1","NofOption":"2","COptionId":"2","Score":"1","isupdated":"0"}}]