我有一个JSON Parser类,如果传递了一个可选参数,就会发送一个Httppost。
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, Object... params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
if(params.length > 0){
httpPost.setEntity(new UrlEncodedFormEntity((List<? extends NameValuePair>)params[0]));
}
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();
} 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;
}
}
这适用于我的ICS和JellyBean设备,但不适用于Froyo和Gingerbread。 错误消息是:
10-21 13:49:10.348: E/Buffer Error(471): Error converting result java.lang.NullPointerException
10-21 13:49:10.348: E/JSON Parser(471): Error parsing data org.json.JSONException: End of input at character 0 of
有人可以帮帮我吗? froyo和gingerbread只支持httpGet ??
答案 0 :(得分:0)
首先检查调用此json字符串的文件,以查找将破坏json格式的无效字符。当我从php文件中获取数据时遇到同样的问题,我的php文件发送了一些额外的错误导致解析为jSONObject失败
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
这就是我在那里遇到错误
答案 1 :(得分:0)
当我尝试在ubuntu的Froyo和gingerbread模拟器中测试它时,它很有趣,它可以工作。但是,当我尝试在Windows中执行它时根本不起作用。所以这是正式关闭:))
答案 2 :(得分:0)
尝试将其放入asynctask
例如
private class PermissionEnableAsyncTask extends AsyncTask<String, Void, Object[]>
{
private ProgressDialog mProgressDialog = null;
@Override
protected void onPreExecute()
{
super.onPreExecute();
mProgressDialog = new ProgressDialog(PermissionList.this);
mProgressDialog.setMessage(Constant.MSG_PROGRESSBAR_WAITING);
mProgressDialog.setCancelable(false);
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.show();
}
@Override
protected Object[] doInBackground(String... params)
{
try
{
String Url = "your URL";
//your logic
return yourlogic;
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
}
@Override
protected void onPostExecute(Object[] object)
{
super.onPostExecute(object);
mProgressDialog.dismiss();
try
{
your logic
}
catch(Exception e)
{
e.printStackTrace();
}
}
}