【问题标题】:How to display JSONObject into TextView on android如何在android上将JSONObject显示到TextView中
【发布时间】:2017-03-02 12:11:18
【问题描述】:

我已经设置了一个 php 脚本来创建 json here,但是当我尝试显示 JSONobject 时,我在我的 Android 监视器上遇到了类似这样的错误..

Value (html)(body)(java.lang.String 类型的脚本无法转换为 JSONObject

谁能告诉我如何解决它?在我的代码下方尝试

我的 MainActivity.java

package flix.yudi.okhttp1;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

    private String TAG = MainActivity.class.getSimpleName();

    private ProgressDialog pDialog;
    private ListView lv;

    // URL to get contacts JSON
    private static String url = "http://zxccvvv.cuccfree.com/send_data.php";

    ArrayList<HashMap<String, String>> contactList;

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

        contactList = new ArrayList<>();

        lv = (ListView) findViewById(R.id.list);

        new GetContacts().execute();
    }

    /**
     * Async task class to get json by making HTTP call
     */
    private class GetContacts extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            HttpHandler sh = new HttpHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url);

            Log.e(TAG, "Response from url: " + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    JSONArray contacts = jsonObj.getJSONArray("");

                    // looping through All Contacts
                    for (int i = 0; i < contacts.length(); i++) {
                        JSONObject c = contacts.getJSONObject(i);

                        String id = c.getString("id");
                        String ask = c.getString("ask");

                        // tmp hash map for single contact
                        HashMap<String, String> contact = new HashMap<>();

                        // adding each child node to HashMap key => value
                        contact.put("id", id);
                        contact.put("ask", ask);

                        // adding contact to contact list
                        contactList.add(contact);
                    }
                } catch (final JSONException e) {
                    Log.e(TAG, "Json parsing error: " + e.getMessage());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),
                                    "Json parsing error: " + e.getMessage(),
                                    Toast.LENGTH_LONG)
                                    .show();
                        }
                    });

                }
            } else {
                Log.e(TAG, "Couldn't get json from server.");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Couldn't get json from server. Check LogCat for possible errors!",
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * */
            ListAdapter adapter = new SimpleAdapter(
                    MainActivity.this, contactList,
                    R.layout.list_item, new String[]{"ask"}, new int[]{R.id.ask});

            lv.setAdapter(adapter);
        }

    }
}

我的 HttpHandler.java

package flix.yudi.okhttp1;

import android.util.Log;

import java.io.BufferedInputStream;
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.ProtocolException;
import java.net.URL;

public class HttpHandler {

    private static final String TAG = HttpHandler.class.getSimpleName();

    public HttpHandler() {
    }

    public String makeServiceCall(String reqUrl) {
        String response = null;
        try {
            URL url = new URL(reqUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());
            response = convertStreamToString(in);
        } catch (MalformedURLException e) {
            Log.e(TAG, "MalformedURLException: " + e.getMessage());
        } catch (ProtocolException e) {
            Log.e(TAG, "ProtocolException: " + e.getMessage());
        } catch (IOException e) {
            Log.e(TAG, "IOException: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
        return response;
    }

    private String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line).append('\n');
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}

我从here得到了参考代码

有人可以帮我解决这个错误吗?

修改后的代码

if (jsonStr != null) {
                try {
                    JSONArray jsonObj = new JSONArray(jsonStr);

                    // Getting JSON Array node
                    JSONArray pertanyaan = jsonObj.getJSONArray("pertanyaan");

                    // looping through All Contacts
                    for (int i = 0; i < pertanyaan.length(); i++) {
                        JSONArray c = pertanyaan.getJSONArray(i);

                        String id = c.getString("id");
                        String ask = c.getString("ask");

编辑

Error
I/OpenGLRenderer: Initialized EGL, version 1.4
E/MainActivity: Response from url: <html><body><script type="text/javascript" src="/aes.js" ></script>
<script>function toNumbers(d){var e=[];d.replace(/(..)/g,function(d){e.push(parseInt(d,16))});return e}function
toHex(){for(var d=[],d=1==arguments.length&&arguments[0].constructor==Array?arguments[0]:arguments,e="",f=0;f<d.length;f++)e+=(16>d[f]?"0":"")+d[f].toString(16);return e.toLowerCase()}
var a=toNumbers("f655ba9d09a112d4968c63579db590b4"),b=toNumbers("98344c2eee86c3994890592585b49f80"),c=toNumbers("455e95bd78dbe99a933749187199f824");
document.cookie="__test="+toHex(slowAES.decrypt(c,2,a,b))+"; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/";
location.href="http://zxccvvv.cuccfree.com/send_data.php?i=1";</script><noscript>This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support</noscript></body></html>
E/MainActivity: Json parsing error: Value <html><body><script of type java.lang.String cannot be converted to JSONArray
V/RenderScript: 0x5598622250 Launching thread(s), CPUs 8

【问题讨论】:

  • 看起来,您在String jsonStr 中接收的数据无效JSON。它有html标签。

标签: java php json android-studio


【解决方案1】:

您的服务器响应是 JsonArray 但您尝试解析为 Json 对象

改变

  JSONObject jsonObject = new JSONObject(jsonStr);

 JSONArray contacts = new JSONArray(jsonStr);

并将下一个操作创建为 JSONArray 而不是 JSONObject

【讨论】:

  • 我已将所有代码从 JSONObject 更改为 JSONArray,但是当我这样做时,一些代码在 String id = c.getString("id ");和 String ask = c.getString("ask");,我已经阅读了 herehere 中的错误,但仍然不知道如何修复它
【解决方案2】:

如果您可以访问服务器,则可以使其返回以下格式的字符串:

{"联系人":[{"id":"1","ask":"pertanyaan ke 1"},{"id":"2","ask":"pertanyaan ke 2"},{ "id":"3","ask":"pertanyaan ke 3"},{"id":"4","ask":"pertanyaan ke 4"},{"id":"5","ask ":"pertanyaan ke 5"}]}

如果您想将其阅读为JSONObjectJSONObject jsonObj = new JSONObject(jsonStr);

然后使用JSONArray contacts = jsonObj.getJSONArray("contacts");解析它


修改后:

把这个JSONArray c = pertanyaan.getJSONArray(i);改成这个JSONObject c = pertanyaan.getJsonObject(i)

【讨论】:

  • 是的先生,我知道 -({"contacts":[{)- 必须显示,但我不知道如何将我的表格显示为 json,尽管我尝试搜索它在 go*gle 中,所以,关于您将 JSONObject 替换为 JSONArray 的想法,我做到了,但在“String id = c.getString("id"); 和 String ask = c.getString("ask" );, " 错误提示“无法应用 JSONArray 中的 getString (int)”
  • JSONArray jsonObj = new JSONArray(jsonStr); // 获取 JSON 数组节点 JSONArray pertanyaan = jsonObj.getJSONArray("pertanyaan"); // 遍历所有联系人 for (int i = 0; i
  • 在循环JSONArray时需要解析内部的JSONObjects
  • 您更新的代码让我的错误消失了,但我的 JSONArray pertanyaan = jsonObj.getJSONArray("pertanyaan");仍然得到同样的错误,我一直在尝试将 JSONArray 更改为 JSONObject,但它使我的代码在循环中出错,,
  • 还没有,先生,我只想将我的问题从数据库显示到文本视图中,
猜你喜欢
  • 2017-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多