简体   繁体   English

解释在Android中收到的Json

[英]Interpreting Received Json in Android

I am here working on my app where m receiving a Json in android. 我在这里在我的应用程序上工作,在那里我在Android中收到Json。 Here is my php script which sends Json. 这是我的发送Json的PHP脚本。

<?php
require_once 'DB_connect.php';
class populatelist{
    private $con;
    private $conn;

    function __construct()
    {
        $this->con = new DB_connect();
        $this->conn = $this->con->connectWithRestaurant();
    }
    function selectallfields(){
        $query = "SELECT * FROM `restaurant_time` LIMIT 50";
        $result = $this->conn->query($query);
        if($result->num_rows >0)
        {
            while($record = $result->fetch_assoc())
            {
                $response['resname'] = $record['Restaurant_name'];
                $response['restadd'] = $record['Address'];
                $response['resttime'] = $record['Waiting_time'];
                $response['images'] = $record['Logo'];
                echo json_encode($response);
            }
            echo json_encode($response);
        }
    }
}


$function = new populatelist();
$function->selectallfields();

?>

And Here is my Android Code For Accepting this Json Request. 这是我的Android代码,用于接受此Json请求。 This is responsible to send data to the custom adapter I have created. 这负责将数据发送到我创建的自定义适配器。

 class Jsonfetch extends AsyncTask<String,Void,ListView>{

    @Override
    protected ListView doInBackground(String... params) {
        try {
            URL url = new URL("http://172.16.16.88/orderspot/populatelist.php");
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setAllowUserInteraction(false);
            InputStream inputStream = httpURLConnection.getInputStream();



            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String temp;
            StringBuilder stringBuilder = new StringBuilder();
            while((temp = bufferedReader.readLine())!=null){
                stringBuilder.append(temp);
            }
            String JsonResponse = stringBuilder.toString();
            Log.i("JsonResposne",JsonResponse);
            try {
                JSONArray new_array =new JSONArray(JsonResponse);
                //int count;

                for(int i = 0, count = new_array.length();i<count;i++){
                    JSONObject jsonObject  = new_array.getJSONObject(i);
                    list.add(new ListModel(jsonObject.getString("resname"),jsonObject.getString("restadd"),jsonObject.getString("resttime"),jsonObject.getString("images")));
                }
                final customAdapter myadapter = new customAdapter(getApplicationContext(),list);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            listView.setAdapter(myadapter);

                        }
                    });
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return listView;
    }
}

I exactly Dont know whats the problem with this code. 我完全不知道这段代码有什么问题。 But perhaps, I'm getting The Json in Invalid Format. 但是也许,我得到的Json格式无效。 And here is my Json Which I receive. 这是我收到的Json。

{"resname":"Sankalp","restadd":"Infocity","resttime":"South Indian","images":"25"}{"resname":"South Cafe","restadd":"Infocity","resttime":"South Indian","images":"20"}{"resname":"Uncle Sam","restadd":"Infocity","resttime":"Pizza","images":"15"}{"resname":"Dangee Dums","restadd":"Infocity","resttime":"Dessert","images":"10"}{"resname":"Fresh Roast","restadd":"Infocity","resttime":"Cafe","images":"5"}{"resname":"Cafe Natrani","restadd":"Infocity","resttime":"Cafe","images":"30"}{"resname":"Chocolate Room","restadd":"Infocity","resttime":"Chocolate","images":"0"}{"resname":"Subway","restadd":"Infocity","resttime":"Sandwich","images":"4"}{"resname":"Jai Bhawani","restadd":"Infocity","resttime":"Breakfast","images":"5"}{"resname":"Jai Bhawani","restadd":"Infocity","resttime":"Breakfast","images":"5"}

Your response from the server is in a JSONObject format. 您从服务器返回的响应为JSONObject格式。 Not a JSONArray 不是JSONArray

Fix your php. 修复您的PHP。

$response = array(); // JSONArray container

while($record = $result->fetch_assoc()) {
    // Build each JSONObject with your desired key names
    $namedRecord = array();
    $namedRecord['resname'] = $record['Restaurant_name'];
    $namedRecord['restadd'] = $record['Address'];
    $namedRecord['resttime'] = $record['Waiting_time'];
    $namedRecord['images'] = $record['Logo'];

    // Insert each object into the array
    array_push($response, $namedRecord);
}

// Output the array of objects
echo json_encode($response);

You are trying to create a JSONArray of JSONObjects which should be formatted like this. 您正在尝试创建JSONObjectsJSONArray ,其格式应如下所示。

[{key:value,key1:value1,...},{anotherObjectKey:anotherObjectValue}]

Print your JSON response in the Log and validate it on.. 在日志中打印您的JSON响应并进行验证。

http://jsonlint.com/ http://jsonlint.com/

Your response is not a valid JSON, it contains many JSONObjects which should be comma separates which they are not, and all of them should be contained inside an JSONArray. 您的响应不是有效的JSON,它包含许多JSONObject,应该用逗号分隔,而不是逗号,并且所有这些都应包含在JSONArray中。 Please format it properly. 请正确格式化。

Check this link on how to build JSONArray in php, 检查此链接,了解如何在php中构建JSONArray,

http://alvinalexander.com/php/php-json_encode-convert-array-to-json-example http://alvinalexander.com/php/php-json_encode-convert-array-to-json-example

Your response should be as, 您的回应应为

"rstaurants" :[
{
"resname": "Sankalp",
"restadd": "Infocity",
"resttime": "South Indian",
"images": "25"
},
{
"resname": "South Cafe",
"restadd": "Infocity",
"resttime": "South Indian",
"images": "20"
},
{
"resname": "Uncle Sam",
"restadd": "Infocity",
"resttime": "Pizza",
"images": "15"
},
{
"resname": "Dangee Dums",
"restadd": "Infocity",
"resttime": "Dessert",
"images": "10"
},
{
"resname": "Fresh Roast",
"restadd": "Infocity",
"resttime": "Cafe",
"images": "5"
}
]

Currently it is, 目前是

{
"resname": "Sankalp",
"restadd": "Infocity",
"resttime": "South Indian",
"images": "25"
}
{
"resname": "South Cafe",
"restadd": "Infocity",
"resttime": "South Indian",
"images": "20"
}
{
"resname": "Uncle Sam",
"restadd": "Infocity",
"resttime": "Pizza",
"images": "15"
}
{
"resname": "Dangee Dums",
"restadd": "Infocity",
"resttime": "Dessert",
"images": "10"
}
{
"resname": "Fresh Roast",
"restadd": "Infocity",
"resttime": "Cafe",
"images": "5"
}

Let me know if it works for you... And do mark it as answer so that it would be useful to others... 让我知道它是否对您有用...并将其标记为答案,以便对其他人有用...

$response = array();

while($record = $result->fetch_assoc()) 
{
    $restaurant = array();
    $restaurant['resname'] = $record['Restaurant_name'];
    $restaurant['restadd'] = $record['Address'];
    $restaurant['resttime'] = $record['Waiting_time'];
    $restaurant['images'] = $record['Logo'];
    $response[] = $restaurant;
}
echo json_encode($response);

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

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