use*_*730 5 parsing android json
可能重复:
JSON解析问题
我正在解析一个JSON文件(这是有效的).它适用于Android 4.0 - 4.0.4但不适用于较旧的Android版本.这是我的清单的一部分:
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="14" />
Run Code Online (Sandbox Code Playgroud)
这是我的解析代码:
public JSONObject getJSONFromUrl(String url) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
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, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}
Run Code Online (Sandbox Code Playgroud)
在旧设备上,我收到以下错误消息(但正如我在新的Android设备上所说的那样):
org.json.JSONException:java.lang.String类型的值无法转换为JSONObject
我完全不知道为什么它在Android 4上运行,但在旧设备上运行.
从这里找到Json
在较新的 Android 版本中,解析器可能JSONObject变得更加宽松。您收到的错误消息似乎是由于可疑的合法 JSON 造成的,特别是在接收端:
我建议您将下载的 JSON 写入文件并与原始文件进行比较,看看下载逻辑是否存在问题。
更新
我无法重现你的问题。使用以下活动从外部存储加载 JSON 在 Android 4.0.3、2.3.3、2.2 和 2.1 上工作得非常好(注意:我很懒,并且硬连线到外部存储的路径):
package com.commonsware.jsontest;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import org.json.JSONException;
import org.json.JSONObject;
public class JSONTestActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
BufferedReader in=
new BufferedReader(new FileReader("/mnt/sdcard/test.json"));
String str;
StringBuilder buf=new StringBuilder();
while ((str=in.readLine()) != null) {
buf.append(str);
buf.append("\n");
}
in.close();
JSONObject json=new JSONObject(buf.toString());
((TextView)findViewById(R.id.stuff)).setText(json.toString());
}
catch (IOException e) {
Log.e(getClass().getSimpleName(), "Exception loading file", e);
}
catch (JSONException e) {
Log.e(getClass().getSimpleName(), "Exception parsing file", e);
}
}
}
Run Code Online (Sandbox Code Playgroud)