\"JSON Data Fetching And Parsing From URL\" with Android Studio problem. Please
ID: 3891818 • Letter: #
Question
"JSON Data Fetching And Parsing From URL" with Android Studio problem.
Please help I'm trying to parse the following JSON file but am not able to do so: api.myjson.com/bins/ z5x5e
Is there anything wrong with my code?
Source Code:
package com.abhishekpanwar.receivedatajson;
import android.os.AsyncTask;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class fetchData extends AsyncTask<Void,Void,Void> {
String data ="";
String dataParsed = "";
String singleParsed ="";
@Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL("https://api.myjson.com/bins/ z5x5e");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while(line != null){
line = bufferedReader.readLine();
data = data + line;
}
JSONArray JA = new JSONArray(data);
for(int i =0 ;i < JA.length(); i++){
JSONObject JO = (JSONObject) JA.get(i);
singleParsed =
"Type:" + JO.get("type") +
"Title:" + JO.get("title") +
"Venue:" + JO.get("venue") +
"Location:" + JO.get("location") +
"Time:" + JO.get("time") +
"Description:" + JO.get("desc") +
"More:" + JO.get("more");
dataParsed = dataParsed + singleParsed;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
MainActivity.data.setText(this.dataParsed);
}
}
Explanation / Answer
Problem is that you are trying to convert a json object using JSONArray and object is not array.
You api returnes
And you are doing
data = // response of API
Because data is not an array because it is not starting with [ and ending with ]
You have to make it as JSON Object like this
This will print
International Conf
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.