您好我是Android编程新手,我正在开发一个项目,将列表转换为json对象并将其存储在服务器中并检索它。我能够将json对象发送到服务器并存储它,但我无法检索它。我应该使用什么方法来检索存储在服务器上的json对象?
答案 0 :(得分:0)
你可以参考下面的类......调用getJSONfromURL(YOUR_POISON_GIRL),方法将返回给你JSONObject。 我希望这会有用
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
JSONObject jObj = null;
String json = "";
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpget);
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 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;
}
}
答案 1 :(得分:0)
要从服务器检索JSON,您必须首先使用DefaultHttpClient
与服务器建立连接。希望您这样做。如果是,请发布您的代码,否则请查看
www.androidhive.info/2012/01/android-json-parsing-tutorial 或者谷歌,当你有URL时,你将有很多帮助来解析JSON。