0
我有一個沒有標題的JSON數組。json閱讀問題數組無標題
我一直試圖閱讀JSON,但它似乎保持失敗。
我希望有一種不調用數組名稱來解析JSON的例子。
任何幫助或指示我的方向的例子將不勝感激。我將在下面附上我有錯誤的代碼。兩個URL是我試圖在讀取數據的
https://www.descartes.com/rest/glossary-items
https://www.descartes.com/rest/glossary-sources
JsonParser:
public class JsonParser {
static InputStream is = null;
static JSONArray jarray = null;
static String json = "";
public JSONArray getJSONFromUrl(String url1) {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url1);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.e("==>", "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// try parse the string to a JSON object
try {
jarray = new JSONArray(builder.toString());
// System.out.println(""+jarray);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jarray;
}
}
doInBackground:
protected Void doInBackground(Void... arg0) {
String str = "";
JsonParser sh = new JsonParser();
// Making a request to url and getting response
String jsonStr = sh.getJSONFromUrl(url1, JsonParser.GET);
if (jsonStr != null){
try{
JSONArray jsonArr = new JSONArray(jsonArr);
test = jsonArr.getJSONObje(str);
// looping through All Contacts
for (int i = 0; i <= str.length(); i++) {
JSONObject c = str.getJSONObject(i);
String tid = c.getString(TAG_TID);
String title = c.getString(TAG_TITLE);
String acronym = c.getString(TAG_ACRONYM);
String description = c.getString(TAG_DESCRIPTION);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_TID, tid);
contact.put(TAG_TITLE, title);
contact.put(TAG_ACRONYM, acronym);
contact.put(TAG_DESCRIPTION, description);
// adding contact to contact list
glossaryList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JsonParser", "Couldn't get any data from the url");
}
return null;
}
粘貼JSON的例子。 – Ali