【问题标题】:PHP SQL array json encode error when converting to java转换为java时PHP SQL数组json编码错误
【发布时间】:2012-11-13 22:31:40
【问题描述】:

我正在将一组 json 的结果回显给 android:

$result = mysql_query($query) or die(mysql_error());
    $resultNo = mysql_num_rows($result);

    // check for successful store
    if ($result != null) {

        $rows = array();
        while($r = mysql_fetch_assoc($result)) {
        $rows[] = $r;
}   
return json_encode($rows);

    } else {
        return false;
    }
}

但是当我尝试在另一端将字符串转换为 JSONObject 时,我得到:

11-13 22:18:41.990: E/JSON(5330): "[{\"email\":\"fish\"}]"

11-13 22:18:41.990: E/JSON Parser(5330): Error parsing data org.json.JSONException: Value [{"email":"fish"}] of type java.lang.String cannot be converted to JSONObject

我已经尝试过使用更大的结果集,并认为这与 null 值有关,但是像上面那样尝试只使用一个值仍然会返回错误。

非常感谢任何帮助

编辑:

Android 方法...

public JSONObject searchPeople(String tower) {
    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", search_tag));
    params.add(new BasicNameValuePair("tower", tower));

    // getting JSON Object
    JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);
    // return json
    return json;
}

JSON 解析器类...

public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {

    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(params));

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
        Log.e("JSON", json);
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);            
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}

【问题讨论】:

  • This 可以帮到你
  • Asok 谢谢,这是我原来的做法,但我在传回行数组时遇到了麻烦。康纳斯我不确定你为什么发布那个链接我在这篇文章中没有提到 JS
  • @EHarpham 当您说“在另一端”时,这是否意味着 Android?如果是这样,您能否向我们展示您的 Android 方面以及来自return json_encode($rows); 的输出。错误代码的第一行告诉我你需要在json_encode之前运行stripslashes
  • 是的,另一端在 android 中。代码在编辑中发布。

标签: php android sql json encode


【解决方案1】:

正如上面提到的@MikeBrant,你需要先通过JSONArray

替换这个:

//try parse the string to a JSON object
try {
    jObj = new JSONObject(json);            
} catch (JSONException e) {
    Log.e("JSON Parser", "Error parsing data " + e.toString());
}

有了这个:

// try parse the string to a JSON object
try {
    JSONArray jArray = new JSONArray(json);        

    for(i=0; i < jArray.length(); i++) {
        JSONObject jObj = jArray.getJSONObject(i);
        Log.i("jObj", "" + jObj.toString());

        // Parsing example
        String email = jObj.getString("email");
        Log.i("email", email);
    }

} catch (JSONException e) {
    Log.e("JSON Parser", "Error parsing data " + e.toString());
}

PHP w/str_replace:

$result = mysql_query($query) or die(mysql_error());
    $resultNo = mysql_num_rows($result);

    // check for successful store
    if ($result != null) {

        $rows = array();
        while($r = mysql_fetch_assoc($result)) {
        $rows[] = $r;
}

$json_string = json_encode($rows);
$json_string = str_replace("\\", "", $json_string, $i);
return $json_string;

    } else {
        return false;
    }
}

【讨论】:

  • 感谢您的回答,但我已经尝试了您的更改并且收到相同的 JSON 错误,即无法转换字符串。斜线现在出现在字符串中,但它仍然无法转换
  • @EHarpham 没问题,让我们尝试解决这个问题。 stripslases() PHP 函数不工作吗?您可以使用其他字符替换功能。请记住,您得到的反斜杠是转义字符,因此您需要转义它们。例如:replaceAll("\\", ""); 会将一个 `` 替换为空。
  • 我已经发布了我目前在编辑中遇到的 json 错误。你是对的我已经测试了带和不带stripslashes的输出,它是一样的,所以stripslashes()不起作用。但是,addslashes() 确实对结果起作用
  • @EHarpham 我刚刚编辑了上面答案的 PHP 部分。我使用您的LogCat 输出进行了测试,并得到了有效的JSON 返回。仅供参考验证JSON 我使用jsonlint.com
  • 试过了,但还是没有运气。我怀疑它与 PHP 中的隐藏字符有关。 Thttp://stackoverflow.com/questions/10267910/jsonexception-value-of-type-java-lang-string-cannot-be-converted-to-jsonobject 第三贴下来???
【解决方案2】:
    $result = mysql_query($query) or die(mysql_error());
    $resultNo = mysql_num_rows($result);

    // check for successful store
    if ($result != null) {

        $rows = array();
        while($r = mysql_fetch_assoc($result)) {
            $rows[] = $r;
        }   
        return json_encode($rows);

    } else {
        return false;
    }

我想这只是你的牙套

【讨论】:

    【解决方案3】:

    您传递给JSONObject 的内容实际上是一个包含单个对象的数组。

    JSONObject 期望语法仅代表包含键值对(即属性)的单个对象。

    您无需传递数组即可使其工作,或者您需要使用JSONArray 来解码 JSON。

    【讨论】:

    • 嗯,Mike,乍一看我也觉得差不多,但是……做一个key=>value数组应该还是合法的
    • 哦,天哪,我错了,这是一个 android 问题,而不是 PHP .. 是的,mike 是对的,这就是你反序列化的方式它不一样你喷出的东西不是你吸的东西在
    • @conners 不符合文档json.org/javadoc/org/json/JSONObject.html。 JSONObject 的外部形式特别提到为string wrapped in curly braces。并且构造函数将这个外部形式转换为对象。
    • 没有值对有没有办法做到这一点?
    • 不确定我是否关注。如果您真正打算传递的是表示数据库行的数组,只需使用JSONArray 而不是JSONObject 就可以了。封闭数组可以在键值对的值部分中保存其他对象或数组。基本上,您只需要根据您想要使用的 JSON 中最外层的数据结构来选择要使用的正确类。
    【解决方案4】:

    当我需要将 json 数据从 php 传递到 java 应用程序时,我遇到了类似的问题,这解决了我的问题:

    $serialliazedParams = addslashes(json_encode($parameters));
    

    【讨论】:

    • 不,它是 php 数组 $serialliazedParams 然后是传递给 java 应用程序的东西,在 java 中: import net.sf.json.JSONObject; ... JSONObject jsonObject = JSONObject.fromObject(args[1]);
    • 谢谢我已经尝试过了,但它似乎添加了更多的斜线。我应该在我的 php 代码中添加哪个值?
    【解决方案5】:

    您需要对 PHP 添加的某些字符进行转义,并为您的 json 字符串添加子字符串以删除返回字符串前面的附加字符。

    一种方法是这样的:

    ANDROID/JAVA 代码

    JSONObject response = new JSONObject(responseString.substring(responseString.indexOf('{'),responseString.indexOf('}') +1).replace("\\",""));
    

    你应该做的更简洁一些,但关键是你必须确保你传入的字符串没有隐藏字符,并且将第一个“””字符替换为空字符,因为它会导致例外。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-17
      相关资源
      最近更新 更多