简体   繁体   English

[更新]如何从json对象访问值?

[英][UPDATE]How do I access values from the json object?

I am completely new to android & JSON. 我是android和JSON的新手。 Please help me out to find a solution for this problem-- Below is my php code. 请帮我找到解决这个问题的方法 - 下面是我的php代码。

    <?php 
require "conn.php";
header('Content-Type: application/json');
if(isset($_POST['mailid']))
{
    $mailid = $_POST['mailid'];
    $today="2017-05-05";//date('Y-m-d');
    $mysql_qry = "select employee_id from employee where employee_email='$mailid';";
    $result = mysqli_query($conn ,$mysql_qry);
    $row = mysqli_fetch_array($result);

    $emp_id=$row['employee_id'];
    if($emp_id)
    {
        $sql = "SELECT count(*) from task where employee_id='$emp_id' and task_date='$today';";
        $result1 = mysqli_query($conn ,$sql);
        $row2=mysqli_fetch_array($result1, MYSQL_ASSOC);

        if($result1) 
        {
            $taskcount['count']= $row2['count(*)'];
            $taskquery = "select task_name from task where employee_id='$emp_id' and task_date='$today';";
            $restask_name=mysqli_query($conn ,$taskquery);

            for($i=0;$row1=mysqli_fetch_array($restask_name);$i++)
            {
                $task_name[]= $row1[0];
            }
            $taskname['tasks']=$task_name;
            $array=array_merge($taskcount,$taskname);
            echo json_encode($array);
        }
        else 
        {
        echo json_encode($taskcount);
        }
    }
    else
    {
        echo "employee ID doesnt match!!";
    }
}
else
{
    echo "post variables are not set";
}
?>

I am getting a response from server like below-- 我收到来自下面的服务器的回复 -

{
 "count": "4",
 "tasks": [
        "collect paper",
        "krishna",
        "mys",
        "bng"   ] 
}

My code to parse json object is as follows-- 我解析json对象的代码如下 -

if (!result.equals("employee ID doesnt match!!") || !result.equals("post variables are not set")) {
                    JSONObject json = new JSONObject(result);

                    MAX_ROWS = Integer.parseInt(json.getString("count"));
                    System.out.println("rows:"+MAX_ROWS);
                    JSONArray tasks = json.getJSONArray("tasks");
                    for (int task_id = 0; task_id < MAX_ROWS; task_id++) {
                        taskname[task_id] = tasks.getString(task_id);//**LINE 153**
                        System.out.println(taskname[task_id]);
                    }

                }

Now I m getting an Null Pointer Exception,Here is my Stacktrace-- 现在我得到一个空指针异常,这是我的Stacktrace--

05-05 17:41:33.255 22823-23024/com.example.anusha.fieldworkemployeetracker W/System.err:java.lang.NullPointerException
05-05 17:41:33.396 22823-23024/com.example.anusha.fieldworkemployeetracker W/System.err:     at com.example.anusha.fieldworkemployeetracker.ViewtaskActivity$BackgroundWorker.doInBackground(ViewtaskActivity.java:153)
05-05 17:41:33.396 22823-23024/com.example.anusha.fieldworkemployeetracker W/System.err:     at com.example.anusha.fieldworkemployeetracker.ViewtaskActivity$BackgroundWorker.doInBackground(ViewtaskActivity.java:107)
05-05 17:41:33.396 22823-23024/com.example.anusha.fieldworkemployeetracker W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:288)
05-05 17:41:33.396 22823-23024/com.example.anusha.fieldworkemployeetracker W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
05-05 17:41:33.396 22823-23024/com.example.anusha.fieldworkemployeetracker W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
05-05 17:41:33.396 22823-23024/com.example.anusha.fieldworkemployeetracker W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
05-05 17:41:33.396 22823-23024/com.example.anusha.fieldworkemployeetracker W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
05-05 17:41:33.396 22823-23024/com.example.anusha.fieldworkemployeetracker W/System.err:     at java.lang.Thread.run(Thread.java:841)

How can I do that? 我怎样才能做到这一点? Thanks in Advance. 提前致谢。

Try following code: 请尝试以下代码:

if (!result.equals("employee ID doesnt match!!") || !result.equals("post variables are not set")) {
                    JSONObject json = new JSONObject(result);
                    //JSONObject count = json.getJSONObject("task" + task_id);
                    JSONArray count = json.getJSONArray("count");
                    MAX_ROWS = Integer.parseInt(count.getString(0));
                    System.out.println("rows:" + MAX_ROWS);
                    for (int task_id = 0; task_id < MAX_ROWS; task_id++) {
                        JSONArray task = json.getJSONArray("task" + String.valueOf(task_id));
                        taskname[task_id] = task.getString(0);
                        System.out.println(taskname[task_id]);
                    }

                }

make Json like ; 让Json喜欢;

       { "count": 
            "4"
          ,
          "tasks0": 
            "collect paper"
          ,
          "tasks1": 
            "krishna"
          ,
          "tasks2": 
            "mys"
          ,
          "tasks3": 
            "bng"
}

Then To parse above JSON use following code; 然后解析JSON之上使用以下代码;

 JSONObject json = new JSONObject(jsonResponseString);
  String countValue = json.getString("count");

There are several mistakes in your code: 您的代码中存在多个错误:

  1. Here you are trying to access JSONArray, using the code of JSONObject . 在这里,您尝试使用JSONObject的代码访问JSONArray。 Eg: count is JSONArray . 例如: countJSONArray So you should parse it as JSONArray . 所以你应该把它解析为JSONArray like this: 像这样:

     MAX_ROWS = json.getJSONArray("count").getInt(0); 
  2. key name is tasks in JSONObject, you should use proper name for that. 密钥名称是JSONObject中的任务,您应该使用适当的名称。

     JSONArray tasks = json.getJSONArray("tasks" + task_id); 
  3. task_name is also a JSONArray , so you should handle that accordingly. task_name也是一个JSONArray ,因此您应该相应地处理它。

So working code should be like this: 所以工作代码应该是这样的:

MAX_ROWS = json.getJSONArray("count").getInt(0);
for (int task_id = 0; task_id < MAX_ROWS; task_id++) {
     JSONArray tasks = json.getJSONArray("tasks" + task_id);
     taskname[task_id] = task.getString("task_name");
     System.out.println(taskname[task_id]);
}

This might solve your problem 这可能会解决您的问题

JSONObject json = new JSONObject(result);
MAX_ROWS = json.getJSONArray("count").getInt(0);
System.out.println("rows:" + MAX_ROWS);
for (int task_id = 0; task_id < MAX_ROWS; task_id++) {
    JSONArray task = json.getJSONArray("tasks" + task_id);
    taskname[task_id] = task.getString(0);
    System.out.println(taskname[task_id]);
}

However I think there is a more structural problem with your JSON String, which makes it difficult to parse into an object. 但是我认为JSON字符串存在更多结构性问题,这使得难以解析为对象。 Namely you're storing everything as a JSONArray (instead of their actual types, eg int or String). 即你将所有内容存储为JSONArray(而不是它们的实际类型,例如int或String)。

Personally I would consider structuring the json like so: 就个人而言,我会考虑像这样构造json:

{
   "count":4,
   "tasks":[
      "collect paper",
      "do Something else",
      "learn about json",
      "learn about gson"
   ]
}

That way you could simply (de)serialize it with a library like Gson using the following POJO: 这样你可以使用以下POJO简单地(de)使用像Gson这样的库来序列化它:

public class TaskHolder {

@SerializedName("count")
@Expose
private Integer count;
@SerializedName("tasks")
@Expose
private List<String> tasks = null;

public Integer getCount() {
return count;
}

public void setCount(Integer count) {
this.count = count;
}

public List<String> getTasks() {
return tasks;
}

public void setTasks(List<String> tasks) {
this.tasks = tasks;
}

}

That way it's a lot easier (imho) to manipulate the data and pass it back and forth. 这样,操作数据并来回传递它会更容易(imho)。 Good luck! 祝好运!

Before directly go straightforward understand what is json and how we use in android. 在直接直接了解什么是json以及我们如何在android中使用之前。

for Json you know there are tow brackets first one is '[ ]' which is display as Json Array and another one is '{ }' which display Json Object, So if you want to parse data from json object then its difficulty if you perfectly understand structure of json data, 对于Json,你知道有两个括号,第一个是'[]',它显示为Json数组,另一个是显示Json对象的'{}',所以如果你想解析json对象的数据那么它的难度如果你完美的话了解json数据的结构,

Here is the example which will explain you json parsing 这是一个解释你json解析的例子

String jsonData="{"data":["a","b","c"]}";

Now if you want to access a then just structure, First one is Object so create JSON Object and put string in Argument. 现在,如果你想访问当时正好的结构,首先是Object,所以创建JSON对象并将字符串放在Argument中。

JSONObject json=new JSONObject(jsonData);

Second one is array so you need to put inside as array, JSONObject and JSONArray Object also provide some defual method which will help to parse data, 第二个是数组,所以你需要把内部作为数组,JSONObject和JSONArray对象也提供一些有助于解析数据的defual方法,

JSONArray jsonArray=json.getJsonArray(postion); JSONArray jsonArray = json.getJsonArray(postion); //postion 1 for 'a' String finalData=jsonArray.getString(0); // postion 1 for'a'String finalData = jsonArray.getString(0);

Now then after try for your code, 现在,在尝试代码之后,

JSONObject json = new JSONObject(result);

                    MAX_ROWS = json.getJSONArray("count").getInt(0);
                    System.out.println("rows:" + MAX_ROWS);
                    for (int task_id = 0; task_id < MAX_ROWS; task_id++) {
                        JSONObject task = json.getJSONArray("task" + task_id);
                        taskname[task_id] = task.getString(0);
                        System.out.println(taskname[task_id]);
                    }

Lets consider your json response as a String result, and use following code to parse the json 让我们将您的json响应视为String结果,并使用以下代码来解析json

String result = "{\"count\": [\"4\"],\"tasks0\": [\"collect paper\"],\"tasks1\": [\"krishna\"],\"tasks2\": [\"mys\"],\"tasks3\": [\"bng\"]}";
        JSONObject json = null;
        try {
            json = new JSONObject(result);
            String countString = json.getJSONArray("count").optString(0, "default_value");
            int MAX_ROWS = Integer.parseInt(countString);

            for (int task_id = 0; task_id < MAX_ROWS; task_id++) {
                String taskString = json.getJSONArray("tasks" + task_id).optString(0, "default_value");
                Log.d("Task Names", taskString);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

Try this; 尝试这个;

if (!result.equals("employee ID doesnt match!!") || !result.equals("post variables are not set")) {
                JSONObject json = new JSONObject(result);

              int  MAX_ROWS = Integer.parseInt(json.getString("count"));
                System.out.println("rows:"+MAX_ROWS);
                String taskname[] = new String[MAX_ROWS];
                JSONArray tasks = json.getJSONArray("tasks");
                for (int task_id = 0; task_id < MAX_ROWS; task_id++) {
                    taskname[task_id] = tasks.getString(task_id);
                    System.out.println(tasks.getString(task_id));
                }

            }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM