【发布时间】:2016-01-05 17:00:51
【问题描述】:
我试图在 android 中解析来自 Wcf 服务的响应,但将我引导到空的 json 对象。所以在这里我附上我的代码,以便以字符串格式从 Wcf 服务获取响应,稍后我将其转换为 JSonObject。请看看这个并尝试告诉我为什么 Jsonobject 是空的或没有值,
private JSONObject doWorkSheetResponse(String URL) {
// TODO Auto-generated method stub
String result = "";
JSONObject jobject = null;
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpResponse response = null;
if (isConnected(getApplicationContext())) {
HttpGet httpget = new HttpGet(URL);
httpget.setHeader("Accept", "application/json");
httpget.setHeader("Content-type", "application/json");
try {
HttpParams httpParameters = httpget.getParams();
// Set the timeout in milliseconds until a
// connection is
// established.
int timeoutConnection = 120000;
HttpConnectionParams.setConnectionTimeout(
httpParameters, timeoutConnection);
// Set the default socket timeout
// (SO_TIMEOUT)
// in milliseconds which is the timeout for
// waiting for data.
int timeoutSocket = 120000;
HttpConnectionParams.setSoTimeout(
httpParameters, timeoutSocket);
response = httpclient.execute(httpget);
if (response != null) {
HttpEntity entity = response.getEntity();
if (entity != null) {
/*
// A Simple JSON Response Read
InputStream instream = entity.getContent();
result = convertStreamToString(instream);
// now you have the string
// representation of the HTML request
System.out.println("RESPONSE: "
+ result);
instream.close();
if (response.getStatusLine()
.getStatusCode() == 200) {
jobject = new JSONObject(result);
}
*/
//Currently using the below code
String buffer = EntityUtils.toString(entity);
if (response.getStatusLine()
.getStatusCode() == 200) {
jobject = new JSONObject(buffer);
}
}
}
}
【问题讨论】:
-
“缓冲区”里面有什么?你用调试器单步调试了吗?
-
buffer 包含字符串格式的 JSON ......哦,对不起,我忘记添加一行,即 jobject = jobject.getJSONObject("MyJsonGetMICData")。
-
是的,它正在工作...感谢您的回复@Arsen
-
response.getStatusLine().getStatusCode()返回什么?也许不是200?缓冲区中的 JSON 长什么样子,可能因为格式不正确而无法解析? -
stackoverflow.com/questions/17260159/… 解释了类似的事情。