我试图简单地获取并解析一些 json,然后将其添加到微调器中。我只需要名称、部分进入第一个微调器,然后当用户选择时将列出该 Json 对象中的主题。
但是,我在将 json 传递到对象“意外的 JSON 异常 org.json.JSONException:在字符 0 处输入结束”时不断收到错误。
下面是我当前的代码:
@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
}
最佳答案
您正在尝试将 JSONArray 解析为 JSONObject。
尝试
JSONArray jsonArray = new JSONArray(result);
而不是
JSONObject jObject = new JSONObject(result);
关于Java - 解析json对象(输入结束于...的字符0),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28596184/