我这里有这段代码,是我从http://mobilesiri.com/json-parsing-in-android-using-android-studio/抓取的并将其修改为自己使用的。
public String makeWebServiceCall(String addr, int requestMethod) {
URL url;
String response = "";
try {
url = new URL(addr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15001);
conn.setConnectTimeout(15001);
conn.setDoInput(true);
conn.setDoOutput(true);
if (requestMethod == Constant.GET) {
conn.setRequestMethod("GET");
} else if (requestMethod == Constant.DELETE) {
conn.setRequestMethod("DELETE");
}
int reqResponseCode = conn.getResponseCode();
if ((requestMethod == Constant.GET || requestMethod == Constant.DELETE) && reqResponseCode == HttpURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
} else {
response = "";
}
} catch (MalformedURLException murle) {
Log.e(MalformedURLException.class.getName(), murle.getMessage());
} catch (IOException ioe) {
Log.e(IOException.class.getName(), ioe.getMessage());
}
return response;
}
将其与普通库一起放在普通的Java环境中,我能够以这种形式获取输出
{"status":"FOUND","data":[{"category_id":3,"category_name":"Experience Sharing Area"},{"category_id":4,"category_name":"Frequently Asked Questions"},{"category_id":1,"category_name":"General Pain Advice"},{"category_id":2,"category_name":"Pain Categorization Section"}]}
将其放在Android中以解析数据,我得到JSONException
-org.json.JSONException:输入的第0个字符的结尾
这是我实现它的地方。
protected Void doInBackground(Void... voids) {
WebRequest webReq = new WebRequest();
String jsonStr = webReq.makeWebServiceCall(Constant.WEB_SERVER_ADDR + Constant.GET_CATEGORY, Constant.GET);
Log.d("URL:", Constant.WEB_SERVER_ADDR + Constant.GET_CATEGORY);
Log.d("Response:", " > " + jsonStr);
categoryList = parseJSON(jsonStr);
return null;
}
这有什么问题吗?
最佳答案
您将得到JSONException:输入的结束字符为0。
发布您的parseJSON类。
{“状态”:“发现”,“数据”:[{“类别ID”:3,“类别名称”:“经验
共享区“},{” category_id“:4,” category_name“:”常见问题
问题“},{” category_id“:1,” category_name“:”一般性疼痛
咨询“},{” category_id“:2,” category_name“:”疼痛分类
部分”}]}
您的解析将是
try {
JSONObject reader = new JSONObject("YOUR_JSON_STRING");
JSONArray jsonArray = reader.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject jsonItem = jsonArray.getJSONObject(i);
try {
jsonItem = jsonArray.getJSONObject(i);
} catch (JSONException e1) {
e1.printStackTrace();
}
String cate_id= jsonItem.getString("category_id");
String category_name= jsonItem.getString("category_name");
}
// Add adapter
} catch (JSONException e) {
e.printStackTrace();
}
}