[英]Parsing json from a file on a server
我正在開發一個 android 項目,該項目從服務器上的文件解析 JSON,並將數據轉換為 java 對象以使用文本視圖顯示數據。
我創建了一個 HTTP 連接,以便應用程序可以向服務器發出 GET 請求以檢索文件的內容。 我還有一個方法可以將 JSON 轉換為字符串並在 logcat 中顯示 JSON,這樣我就知道 GET 請求成功了。
我將一個包含 url 的字符串傳遞給服務器並使用我的 HttpHandler 建立連接。
private class parseJSON extends AsyncTask<Void, Void, List<Book>> {
private final String TAG = parseJSON.class.getSimpleName();
@Override
protected List<Book> doInBackground(Void... voids) {
Log.i(TAG, "Start Async to get books.");
ArrayList<Book> bookArray = new ArrayList<>(0);
String jsonUrl = getApplication().getString(R.string.json_feed);
HttpHandler httpHandler = new HttpHandler();
String jsonString = httpHandler.makeJsonServiceCall(jsonUrl);
Log.i(TAG, "Response from url: " + jsonString);
if( jsonString != null) {
try {
JSONObject jsonObject = new JSONObject(jsonString);
// Get JSON array node.
JSONArray jArray = jsonObject.getJSONArray("book");
// Looping through all the books.
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonEntry = jArray.getJSONObject(i);
String year = jsonEntry.getString("year");
String title = jsonEntry.getString("title");
String publisher = jsonEntry.getString("publisher");
String price = "£" + jsonEntry.getString("price");
final Book bookObject = new Book(year, title, publisher, price);
//Add the new books to our result array.
bookArray.add(bookObject);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return bookArray;
}
@Override
protected void onPostExecute( List<Book> books) {
super.onPostExecute(books);
Log.e(TAG, "Populate UI recycler view with json converted data.");
// bookArray
bookList.setValue(books);
}
}
當我嘗試獲取數組節點時,解析似乎被中斷了。
出現以下問題:
org.json.JSONException: Value "Contents of my json file"
at org.json.JSON.typeMismatch(JSON.java:101)
at org.json.JSONObject.getJSONArray(JSONObject.java:591)
然后引用第 170 行,它是:
// Get JSON array node.
JSONArray jArray = jsonObject.getJSONArray("book");
我會不會在解析過程中做錯了什么?
您的解析沒有問題,但是您的 JSONPath 很糟糕。 看看你的原始結構。 實際路徑是$.bib.book
,因此要獲取該數組,您需要執行
new JSONObject(jsonString).getJSONObject("bib").getJSONArray("book")
您也許可以執行.getJSONArray("bib.book")
但我不確定該類如何解析 JSON 以及是否支持嵌套路徑。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.