dongtiao0279 2016-06-18 18:04
浏览 60

当我用服务器中的几十个对象编码一个数组时,空json

I have some problems with communication from server to my android app. When I send a json in which there is an array with few dozen of data, something goes wrong.

This is what the server returns when there aren't record that satisfies my conditions:
It is displayed with Log.e(TAG, json.toString());
{"comuni":[]}

This is what the server returns when the sql statement found some raws.
It is displayed with Log.e(TAG, json.toString());

    {"comuni": [
        {
            "codCatastale": "D546",
            "nomeComune": "Pianopoli",
            "cap": "88040",
            "codProvincia": "CZ"
        },
        {
            "codCatastale": "G541",
            "nomeComune": "Piana di Monte Verna",
            "cap": "81013",
            "codProvincia": "CE"
        },
        {
            "codCatastale": "G542",
            "nomeComune": "Piana Crixia",
            "cap": "17058",
            "codProvincia": "SV"
        },
        {
            "codCatastale": "G543",
            "nomeComune": "Piana degli Albanesi",
            "cap": "90037",
            "codProvincia": "PA"
        },
        {
            "codCatastale": "G546",
            "nomeComune": "Pian Camuno",
            "cap": "25050",
            "codProvincia": "BS"
        },
        {
            "codCatastale": "G547",
            "nomeComune": "Piancastagnaio",
            "cap": "53025",
            "codProvincia": "SI"
        },
        {
            "codCatastale": "G549",
            "nomeComune": "Piancogno",
            "cap": "25052",
            "codProvincia": "BS"
        },
        {
            "codCatastale": "G551",
            "nomeComune": "Piandimeleto",
            "cap": "61026",
            "codProvincia": "PU"
        },
        {
            "codCatastale": "G552",
            "nomeComune": "Pian di Sco",
            "cap": "52026",
            "codProvincia": "AR"
        },
        {
            "codCatastale": "G553",
            "nomeComune": "Piane Crati",
            "cap": "87050",
            "codProvincia": "CS"
        },
        {
            "codCatastale": "G555",
            "nomeComune": "Pianella",
            "cap": "65019",
            "codProvincia": "PE"
        },
        {
            "codCatastale": "G556",
            "nomeComune": "Pianello del Lario",
            "cap": "22010",
            "codProvincia": "CO"
        },
        {
            "codCatastale": "G557",
            "nomeComune": "Pianello Val Tidone",
            "cap": "29010",
            "codProvincia": "PC"
        },
        {
            "codCatastale": "G558",
            "nomeComune": "Pianengo",
            "cap": "26010",
            "codProvincia": "CR"
        },
        {
            "codCatastale": "G559",
            "nomeComune": "Pianezza",
            "cap": "10044",
            "codProvincia": "TO"
        },
        {
            "codCatastale": "G560",
            "nomeComune": "Pianezze",
            "cap": "36060",
            "codProvincia": "VI"
        },
        {
            "codCatastale": "G561",
            "nomeComune": "Pianfei",
            "cap": "12080",
            "codProvincia": "CN"
        },
        {
            "codCatastale": "G564",
            "nomeComune": "Pianico",
            "cap": "24060",
            "codProvincia": "BG"
        },
        {
            "codCatastale": "G565",
            "nomeComune": "Pianiga",
            "cap": "30030",
            "codProvincia": "VE"
        },
        {
            "codCatastale": "G568",
            "nomeComune": "Piano di Sorrento",
            "cap": "80063",
            "codProvincia": "NA"
        },
        {
            "codCatastale": "G570",
            "nomeComune": "Pianoro",
            "cap": "40065",
            "codProvincia": "BO"
        },
        {
            "codCatastale": "G571",
            "nomeComune": "Piansano",
            "cap": "1010",
            "codProvincia": "VT"
        },
        {
            "codCatastale": "G572",
            "nomeComune": "Piantedo",
            "cap": "23010",
            "codProvincia": "SO"
        }
    ]
}

And this is what it returns when the raws that are found are more then some dozen. With 80 records already gives this error.
It is displayed with Log.e(TAG, "Malformed Json string: " + json.toString() + e.getMessage());

06-18 19:02:07.012 13689-13689/com.example.alberto.easyfood E/CommunicationManager: Could not parse malformed JSON: End of input at character 0 of json string:

Like you can see the json string is empty.

This is my php code:

<?php

/*** Opening the connection with the db ***/
include 'open_db_connection.php';

define('RESIDENCES', 'comuni');

try {
  /*** Getting data ***/
  $json = file_get_contents("php://input");
  /*** Decoding json ***/
  $data = json_decode($json, TRUE);
  $residence = $data[ATTR_RESIDENCE_NAME];
  if($residence != ""){
    print(json_encode((getResidences($residence))));
  }else return null;

} catch(Exception $e) {
  echo $e->getMessage();
}

$conn = null;



/**
 * Function that return an array of arrays containing information about residences begginning with the same initials letters that are passed at this functon.
 * For each residence there will be also the other information like the province id.
 * Parameters:
 *  Residence (it can be the full name or only the initials letters)
 */
function getResidences($residence){
  global $conn;
  /*** Preparing the SQL statement ***/
    $stmt = $conn->prepare('SELECT * FROM '.TABLE_RESIDENCES.' WHERE '.ATTR_RESIDENCE_NAME.' LIKE :residence');
  /*** Binding parameters ***/
  $param = "$residence%";
  $stmt->bindParam(':residence', $param);
  /*** exceute the query ***/
  $stmt->execute(); 

  /*** Setting the type of array (in this case it will be an associative array)***/
  $residences[RESIDENCES] = $stmt->FetchAll(PDO::FETCH_ASSOC);
  return $residences;
}

?>

This is my java code

Here there is the method that passes the Url of my php page and a JSONObject to be sent

public String[] getResidences(String residence_initials, Context context){
    JSONObject json = new JSONObject();
    if(!residence_initials.isEmpty()){
        try {
            json.put(DB_RESIDENCE, residence_initials);
            json = CommunicationManager.postData(URL_RESIDENCES, json);
            if(json != null){
                JSONArray jsonArray = json.getJSONArray(RESIDENCES);
                Log.e(TAG, json.toString());
            }
        } catch (JSONException e) {
            Log.e(TAG, "Malformed Json string: " + json.toString() + e.getMessage());
        }
    }
    return null;
}

And this is the static method that send my json to the server and returns a JSONObject that might be the response

private static final int READ_TIMEOUT = 8000;
private static final int CONNECTION_TIMEOUT = 10000;
private static final String POST_METHOD = "POST";
public static JSONObject postData(String url, JSONObject dataToBeSent){
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    JSONObject jsonObject = null;
    if(dataToBeSent != null) {
        URL serverURL = null;
        StringBuilder stringBuilder = new StringBuilder();
        try {
            serverURL = new URL(url);
            /* Opening a connection */
            HttpURLConnection connection = (HttpURLConnection) serverURL.openConnection();
             /* Setting timeout */
             connection.setReadTimeout(READ_TIMEOUT);
             connection.setConnectTimeout(CONNECTION_TIMEOUT);
             /* Using the POST method sending data */
             connection.setRequestMethod(POST_METHOD);
             connection.setDoInput(true);
             connection.setDoOutput(true);
             DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
             outputStream.writeBytes(dataToBeSent.toString());
             outputStream.flush();
             outputStream.close();
             connection.connect();

             /* Getting the response */
             int responseCode = connection.getResponseCode();
             if(responseCode == HttpsURLConnection.HTTP_OK) {
                 /* If the response is a 200 http response it will get the message the server sent */
                 String line;
                 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                 while ((line = bufferedReader.readLine()) != null) {
                     stringBuilder.append(line + '
');
                 }

                 jsonObject = new JSONObject(stringBuilder.toString());
             }

             connection.disconnect();
         } catch (MalformedURLException e) {
             Log.e(TAG, "MalformedURLException: " + e.getMessage());
         } catch (IOException e) {
             Log.e(TAG, "IOException: " + e.getMessage());
         } catch (JSONException e) {
             Log.e(TAG, "Could not parse malformed JSON: " + e.getMessage() + "
json string: "+ stringBuilder);
         }

     }
     /* Return a JSON Object*/
     return jsonObject;
}
  • 写回答

1条回答 默认 最新

  • duangai1941 2016-06-18 18:10
    关注

    I have doubt on this line -

    JSONArray jsonArray = json.getJSONArray(RESIDENCES);
    

    Check the value of RESIDENCES it must be comuni.

    Hope it will help :)

    评论

报告相同问题?

悬赏问题

  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误