我在 Eclipse ADT 上进行了 JSON 解析,并且运行完美。但是,当在 Android Studio 上使用相同的代码时,它在 DefaultHttpClient 和该块中的所有其他单词中显示错误。
这是我的 JSON 解析器类
JSONParser.java
public class JSONParser {
JSONArray cArray;
JSONObject jsonObj;
InputStream is = null;
String jsonStr = "";
String urlString;
Context context;
String id;
String name, email, mobile;
Contacts contacts;
List < Contacts > contactList;
public JSONParser() {
// TODO Auto-generated constructor stub
}
public JSONParser(String url) {
this.urlString = url;
}
public List < Contacts > getString() {
contactList = new ArrayList < Contacts > ();
try {
// **Error in this block**
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(urlString);
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();
} catch (NullPointerException e) {
Log.e("NULL DATA", "cant fetch " + e.toString());
}
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();
jsonStr = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
if (jsonStr != null) {
try {
cArray = new JSONArray(jsonStr);
JSONObject jsonObj = null;
// looping through All Contacts
for (int i = 0; i < cArray.length(); i++) {
jsonObj = cArray.getJSONObject(i);
id = jsonObj.getString("foodno");
name = jsonObj.getString("foodname");
email = jsonObj.getString("foodtype");
/* JSONObject phoneNo = jsonObj.getJSONObject("phone");
mobile = phoneNo.getString("mobile");*/
contacts = new Contacts(id, name, email);
// adding contact to contact list
contactList.add(contacts);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
} else {
Log.e("JSONParser", "Couldn't get any data from the url");
}
return contactList;
}
}
谁能建议如何连接以获取可以传递给 BufferedReader 的 json 字符串?
我强烈建议您使用图书馆来完成这项工作。你可以使用GSON lib https://github.com/google/gson(由谷歌开发)或杰克逊·利布 https://github.com/FasterXML/jackson。对于您可以使用的请求改造库 http://square.github.io/retrofit/(由 Square 开发)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)