[英]How Do I fetch data inside this json file
{ "createTeacher":{ "prefix":"ghs-", "name":"TeacherA", "email":"TeacherA", "password":"TeacherA", "username":"TeacherA", "classboard" :“CBSE”、“classgrade”:“VII”、“classsection”:“A”、“subjectboard”:“CBSE”、“subjectgrade”:“VII”、“subjectsection”:“A”、“subject”:”數學” } }
如果您使用的是 vanilla JS,則可以使用 Fetch API;如果您使用的是 React,則可以使用 Axios。
獲取 API 只是從 API 獲取數據。
fetch('https://reqres.in/api/users/23')
.then(res=>{
if (res.ok) {
console.log('Success');
} else {
console.log('Failed');
}
return res.json();
})
.then(data=>console.log(data))
.catch(err=>console.log('ERROR'));
正如您在上面看到的,它是鏈式方法,因為這是基於承諾的。 第一種方法只是從 URL 中獲取,或者如果您願意,您可以通過指定目錄在文件中執行此操作。
第二種方法返回響應,這是奇怪的部分,因為它仍應轉換為 JSON 否則它將返回奇怪的 output 這也有利於檢查來自請求的響應,即 Z293C9EA246FF5 為什么有這樣的語句'785DC6ZF62A'6檢查請求是否成功,如果它是本地文件,則不需要,在 HTTP 狀態檢查之后的下一行是將響應轉換為 JSON,並且應該返回它以便能夠訪問數據到下一個then
是 function。
第三種方法是您可以訪問數據的地方。 最后,它會捕獲錯誤。
您也可以在異步中實現它。
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getActivity().getAssets().open("yourfilename.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
並使用這種方法
try {
JSONObject obj = new JSONObject(loadJSONFromAsset());
JSONArray m_jArry = obj.getJSONArray("formules");
ArrayList<HashMap<String, String>> formList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> m_li;
for (int i = 0; i < m_jArry.length(); i++) {
JSONObject jo_inside = m_jArry.getJSONObject(i);
Log.d("Details-->", jo_inside.getString("formule"));
String formula_value = jo_inside.getString("formule");
String url_value = jo_inside.getString("url");
//Add your values in your `ArrayList` as below:
m_li = new HashMap<String, String>();
m_li.put("formule", formula_value);
m_li.put("url", url_value);
formList.add(m_li);
}
} catch (JSONException e) {
e.printStackTrace();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.