我现在正在Eclipse中开发一系列问题后,我正在尝试使用以下语法解析JSONObject:
{"d":
[
{"PartitionKey":"fec35985-5e82-47b4-94da-4aed9da9bf72",
"RowKey":"b8a57f4a-e057-4b43-9f49-99fa7d19d6a0",
"codigo_dane":"115183000392",
"nombre_de_la_institucion":"I.E. JOSE MARIA POTIER",
"nombre_sede_educativa":"PRINCIPAL",
"rector":"MIGUEL ALBERTO MEDINA RUIZ",
"direccion":"KRA. 7 No. 4-58",
"telefono":"7892195",
"correo_electronico":"chita_josemariapotier@desboyaca.gov.co",
"no_de_estudiantes":"250"},
{"PartitionKey": ...
}
]
}
使用此方法来请求JSONObject:
public static JSONObject requestWebService(String serviceUrl){ disableConnectionReuseIfNecessary();
HttpURLConnection urlConnection = null;
try {
// create connection
URL urlToRequest = new URL(serviceUrl);
urlConnection = (HttpURLConnection)
urlToRequest.openConnection();
urlConnection.setConnectTimeout(CONNECTION_TIMEOUT);
urlConnection.setReadTimeout(DATARETRIEVAL_TIMEOUT);
// handle issues
int statusCode = urlConnection.getResponseCode();
if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
// handle unauthorized (if service requires user login)
} else if (statusCode != HttpURLConnection.HTTP_OK) {
// handle any other errors, like 404, 500,..
}
// create JSON object from content
InputStream in = new BufferedInputStream(
urlConnection.getInputStream());
return new JSONObject(getResponseText(in));
} catch (MalformedURLException e) {
// and a lot of other exceptions; I don't include them to keep this short
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
当我尝试使用此方法接收JSONObject(它似乎直到现在才有效;我过去常常得到一些JSONExceptions但我现在没问题):
public List<String> getAllItemsNames(JSONObject JObject) {
List<String> names = new ArrayList<String>();
try {
JSONArray objs = JObject.getJSONArray("d");
for(int i = 0; i < objs.length(); i++) {
JSONObject obj = objs.getJSONObject(i);
names.add(obj.getString(KEY_NAME));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
names.add("No values available!");
e.printStackTrace();
}
return names;
}
我收到错误:“d没有值”。我认为这可能是因为数组的名称而发生的,因为我不确定它是否真的是“d”。我尝试了一个空格(“”),但我仍然得到例外。请帮忙!