我试图接收一个JSON格式文件,在Android中抛出HTTP。但我这样做,我猜文件格式不好。代码如下:
@Override
protected String doInBackground(String... params) {
StringBuilder builder = new StringBuilder();
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
URI website = new URI(params[0]);
HttpGet request = new HttpGet();
request.setHeader("Content-type", "application/json");
request.setURI(website);
HttpResponse httpResponse = httpClient.execute(request);
HttpEntity entity = httpResponse.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
builder.append(line);
}
}
catch(Exception e){
Log.e("http", e.toString());
}
return builder.toString();
}
@Override
protected void onPostExecute(String result) {
try {
JSONObject jObject = new JSONObject(result);
txt.setText((String) jObject.get("shortName"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//txt.setText(result);
}
JSON文件是这样的:
{"lectiveSemesters":[{"lectiveSemesterId":1,"shortName":"0910i","startYear":2009,"term":1,"termName":"Fall","_links":{"self":"http://thoth.cc.e.ipl.pt/api/v1/lectivesemesters/1","root":"http://thoth.cc.e.ipl.pt/api/v1"}},{"lectiveSemesterId":2,"shortName":"0910v","startYear":2009,"term":2,"termName":"Spring","_links":{"self":"http://thoth.cc.e.ipl.pt/api/v1/lectivesemesters/2","root":"http://thoth.cc.e.ipl.pt/api/v1"}},{"lectiveSemesterId":3,"shortName":"1011i","startYear":2010,"term":1,"termName":"Fall","_links":{"self":"http://thoth.cc.e.ipl.pt/api/v1/lectivesemesters/3","root":"http://thoth.cc.e.ipl.pt/api/v1"}},
...
...
"_links":{"self":"http://thoth.cc.e.ipl.pt/api/v1/lectivesemesters"}}
这只是文件的一部分。
我做错了吗?我包含了标题以便以JSON格式接收。
答案 0 :(得分:1)
你在这里。
try{
JSONObject jObject = new JSONObject(result);
JSONArray jarray = jObject.getJSONArray("lectiveSemesters");
for(int i = 0; jarray != null & i < jarray.length(); i++){
JSONObject jitem = (JSONObject) jarray.get(i);
}
} catch (Exception e){
}