我正在尝试以这种格式下载JSON文件
[ { “CRN”: “10001”, “课程”: “REG1” }, { “CRN”: “10002”, “课程”: “REG2” } ]
我知道如何在创建JSONArray类时使用它,但我不知道如何从文件创建JSONArray对象。如果文件的URL位置是“www.test.com”,我将如何在启动应用程序时在后台下载它,以免干扰应用程序的启动但不要求用户手动自己下载。
答案 0 :(得分:0)
您可能想要查看这个有用的库:Retrofit
它使得抓取和解析JSON数据变得容易!
答案 1 :(得分:0)
我认为您应该寻找Android Web Service示例。在哪里可以找到有关
的信息1.如何向服务器发出HTTP请求(使用URL,例如www.google.com) 2.如何处理来自服务器的响应 3.如何从服务器等解析JSON / XML响应。
这是我找到的简单教程。
一步一步走。
在示例中,我们向服务器请求登录并获得响应,然后继续在app。
这是代码snipp。
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
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();
Log.e("JSON", json);
} 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;
}
}
答案 2 :(得分:0)
自动下载JSON文件的一种好方法是在家庭活动的AsyncTask
方法中启动onCreate
。
JSON文件只不过是特殊格式的文本文件,因此可以轻松地从HttpURLConnection
作为响应下载,然后将其视为字符串。
将JSON对象解析为Java对象的建议是Jackson JSON处理器。您可以使用此库的类ObjectMapper自动创建对象。
如果您计划自己实现服务器端,并且还需要一个库来发送JSON对象,则可以在服务器和客户端上使用Jersey 。