【发布时间】:2020-05-02 19:09:54
【问题描述】:
private void getWebApiData() {
String WebDataUrl = "myjsonfileurl";
new AsyncHttpTask.execute(WebDataUrl);
}
@SuppressLint("StaticFieldLeak")
public class AsyncHttpTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpsURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpsURLConnection) url.openConnection();
if (result != null) {
String response = streamToString(urlConnection.getInputStream());
parseResult(response);
return result;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
if (result != null) {
newsAdapter = new NewsAdapter(getActivity(), newsClassList);
listView.setAdapter(newsAdapter);
Toast.makeText(getContext(), "Data Loaded Successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "Failed to load data!", Toast.LENGTH_SHORT).show();
}
progressBar.setVisibility(View.GONE);
}
}
private String streamToString(InputStream stream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
String line;
String result = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
// Close stream
if (null != stream) {
stream.close();
}
return result;
}
private void parseResult_GetWebData(String result) {
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray("books");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject articleObject = jsonArray.getJSONObject(i);
JSONObject sourceObject = articleObject.getJSONObject("A");
String name = sourceObject.optString("name");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
我的 json 文件
{
"books": [
{
"A": [
{
"Amazonite": {
"name": "Amazonite",
"image": "www.google.com"
},
"Amethyst": {
"name": "Amethyst",
"image": "www.google.com"
}
}
],
"B": [
{
"Beryl": {
"name": "Beryl",
"image": "www.google.com"
},
"BloodStone": {
"name": "Bloodstone",
"image": "www.google.com"
}
}
]
}
]
}
我想要的是如何获取字母 A 下的数据值,即 Amazonite 和 Amethyst 以及字母 B 下的数据值,但我可以只给我空文本字段,没有任何数据被填充。 我已尝试使用此代码,但值返回“null”
private void parseResult_GetWebData(String result) {
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray("books");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject articleObject = jsonArray.getJSONObject(i);
String name = String.valueOf(articleObject.optJSONObject("A"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
【问题讨论】:
-
A是一个 JSON 数组,所以你应该改用articleObject.optJSONArray("A")。 -
试过了,但我得到了 A 节点的完整字符串 "[ { "Amazonite": { "name": "Amazonite", "image": "www.google.com" }, "Amethyst": { "name": "Amethyst", "image": "www.google.com" } } ],"什么是“Amazonite and Amethyst”的关键
-
我只是指出为什么你得到
null变量name。
标签: java android arrays json android-studio