LandL Partners LandL Partners - 3 months ago 23
Java Question

Java - Parsing json object (end of input at character 0 of ...)

I am trying to simply get and parse some json to then be added into a spinner. I simply require the name, section to go into the first spinner then as the user selects that would list the subjects within that Json Object.

However I keep getting an error with pasrsing the json to the object 'unexpected JSON exception org.json.JSONException: End of input at character 0 of'.

Below is my current code:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

new HttpAsyncTask().execute("http://example.org");
}

public static String GET(String url)
{
InputStream inputStream = null;
String result = "";
try {
// create HttpClient
HttpClient httpclient = new DefaultHttpClient();

// make GET request to the given URL
HttpResponse httpResponse = httpclient.execute(new HttpGet(url));

// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();

// convert inputstream to string
if(inputStream != null) {
result = convertInputStreamToString(inputStream);
}
else {
result = "Did not work!";
}

}
catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}

return result;
}

private static String convertInputStreamToString(InputStream inputStream) throws IOException
{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null) {
result += line;
}

inputStream.close();
return result;
}

public boolean isConnected()
{
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
return true;
}
else {
return false;
}
}

private class HttpAsyncTask extends AsyncTask<String, Void, String>
{
@Override
protected String doInBackground(String... urls) {
return GET(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result)
{
try {
JSONObject jObject = new JSONObject(result);
//qualifications = jObject.getJSONArray("name");
bindSpinners();
}
catch(JSONException e) {
Log.e("JSON", "unexpected JSON exception", e);
}
}
}

private void bindSpinners() {
// I will pass the JObject data here to be used to bind to the relevent spinners
}

Answer

You are trying to parse a JSONArray as a JSONObject.

Try

JSONArray jsonArray = new JSONArray(result);

instead of

JSONObject jObject = new JSONObject(result);  
Comments