簡體   English   中英

從Android Java和PHP REST API解析JSON的異常

[英]Exception parsing JSON from Android Java and PHP REST API

我想發送一個像這樣的JSON:

{"reverseme" : "Reverse Me!" }

所以我創建了這個Java:

JSONObject jsonToSend = new JSONObject()
    .put("reverseme", "Reverse ME!")

如果我將它轉換為String並將其發送到我的api我沒有問題:

HttpClient client = new HttpClient();
HttpPost post = new HttpPost("http://192.168.0.10/api");

List<NameValuePair> postData= new ArrayList<NameValuePair>();
postParams.add(new BasicNameValuePair("json", jsonToSend.toString()));

post.setEntity(new UrlEncodedFormEntity(postData));

它會轉到我的PHP API就像這樣簡單(我正在測試一些東西):

<?php 
$JSON = json_decode($_POST['json'], true);

print(
    json_encode( Array(
        'reversed' : strrev($JSON['reverseme'])
    ))
); ?>

最后,Java Code讀取響應是這樣的:

HttpResponse httpresponse = client.execute(post);
String jsonstringresponse = EntityUtils.toString(httpresponse.getEntity()); 
JSONObject jsonresponse = new JSONObject(jsonstringresponse);

它給了我這個StackTrace:

org.json.JSONException: A JSONObject text must begin with '{' at character 1 of "{\"reversed\": "!EM esreveR"}"
    at org.json.JSONTokener.syntaxError(JSONTokener.java:448)
    at org.json.JSONObject.<init>(JSONObject.java:178)
    at org.json.JSONObject.<init>(JSONObject.java:246)
 -> at com.example.test.MainActivity.onClick(MainActivity.java:67)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:521)
    at android.view.View$1.onClick(View.java:2026)
...

當然,我可以在StackTrace的最后一行看到我有一些Android UI,它可以從EditText中讀取並將JSONresult放到TextView中。

問題是從服務器來它:

"{\"reversed\": "!EM esreveR"}"

這里有什么問題? 為什么json_encode會逃避每個角色? 是Charset問題還是需要清潔什么?

謝謝你的任何建議。


更新1在Apache錯誤日志中,我找到了這一行:

[error] PHP Warning:  json_encode(): Invalid UTF-8 sequence in argument in /var/www/controllers/api.inc.php on line 4.

我以為它甚至可能是PHP錯誤配置?


更新2

json_encode正在接收西班牙語字符串,這就是錯誤的原因:閱讀“Atención”會因為'ó'而出錯。

我暫時使用stripslashes()並刪除第一個和最后一個字符以使其工作。

是服務器配置錯誤,並且PHP保存在ISO-8859-1字符集上,因此PHP混亂了3個不同的字符集。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM