首先,这是我的json输出。
{“alert_id”:“1”,“类型”:“紧急”,“部门”:“工程部”,“clas”:“4”,“教师”:“软件工程”,“正文”: “迈克”, “日期”: “1990年4月10日”}
这是解析代码。
package com.androidalert;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
public class AlertsJSON extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alert);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.tuncayyildirim.com.tr/cagri_android_frontend/event_restful/event_handler/get_event.json");
EditText textID = (EditText) findViewById(R.id.textID);
EditText textType = (EditText) findViewById(R.id.textType);
EditText textDepartment = (EditText) findViewById(R.id.textDepartment);
EditText textClass = (EditText) findViewById(R.id.textClass);
EditText textFaculty = (EditText) findViewById(R.id.textFaculty);
EditText textBody = (EditText) findViewById(R.id.textBody);
EditText textDate = (EditText) findViewById(R.id.textDate);
textID.setKeyListener(null);
textType.setKeyListener(null);
textDepartment.setKeyListener(null);
textClass.setKeyListener(null);
textFaculty.setKeyListener(null);
textBody.setKeyListener(null);
textDate.setKeyListener(null);
try {
HttpResponse response = httpclient.execute(httppost);
String jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
JSONObject object = new JSONObject(jsonResult);
String id = object.getString("alert_id");
String type = object.getString("type");
String department = object.getString("department");
String clas = object.getString("clas");
String faculty = object.getString("faculty");
String body = object.getString("body");
String date = object.getString("date");
textID.setText(id);
textType.setText(type);
textDepartment.setText(department);
textClass.setText(clas);
textFaculty.setText(faculty);
textBody.setText(body);
textDate.setText(date);
} catch (JSONException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
e.printStackTrace();
}
return answer;
}
}
我认为,代码是正确的但我无法在我的应用程序中显示JSON输出。
答案 0 :(得分:0)
JSON对象解析看起来是正确的,所以问题在于其他问题。首先,你不应该(并且实际上不能在最近的sdks中)在UI线程上进行网络连接。另外,如果收到实际的json,我会在解析之前检查你的“jsonResult”值。