【问题标题】:Java string to json objectJava 字符串到 json 对象
【发布时间】:2015-04-16 16:31:16
【问题描述】:

我正在尝试将 Json 与 android 一起使用 我有一个返回 Json 字符串的链接

InputStream is = new URL(url).openStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);

但是,在制作一个新的 JSONObject(jsonText);它压碎了。

这是我的网址:http://igorsdomain.byethost3.com/getUser.php?username=SailorBoogy&password=qwerty&event=2222

这是返回的对象:{"ID":"23","Username":"SailorBoogy","Password":"qwerty","eventID":"6"}

我也试过JSONObject(jsonText.replaceAll("\"" , "\\\\\"")); 但它没有用。

有什么问题?我用错了吗?

Json 库:

org.json.JSONException; org.json.JSONObject; org.json.JSONStringer;

【问题讨论】:

  • 您使用的是哪个 JSON 库? Java、Jackson 等中的 JSON?

标签: android json jsonobject


【解决方案1】:

我强烈推荐你使用Volley、Loopj、Okhttp等网络库进行网络操作。

这是解决您问题的代码。

class LongOpreation extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {

        String str = "";

        try {
            str = sendGetRequest();

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return str;
    }

    public String sendGetRequest() throws MalformedURLException {
        StringBuilder response = new StringBuilder();
        String requrl = "";
        requrl = "http://igorsdomain.byethost3.com/getUser.php?username=SailorBoogy&password=qwerty&event=2222";
        response = requestExecuter(requrl);


        return response.toString();

    }


    @Override
    protected void onPostExecute(String result) {
        try {
            JSONObject jsonObject = new JSONObject(result);
            System.out.println("json-----------------------"+jsonObject);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    @Override
    protected void onPreExecute() {

    }
    public StringBuilder requestExecuter(String str) {
        StringBuilder response = new StringBuilder();
        try {
            URL url = new URL(str);

            HttpURLConnection httpconn = (HttpURLConnection) url
                    .openConnection();
            httpconn.setConnectTimeout(5000);
            httpconn.setReadTimeout(10000);

            if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                BufferedReader input = new BufferedReader(
                        new InputStreamReader(httpconn.getInputStream()));
                String strLine = null;
                while ((strLine = input.readLine()) != null) {
                    response.append(strLine);

                }
                input.close();
            }
            } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return response;
    }
}

简单地调用new LongOperation().execute("");,你就完成了

【讨论】:

    【解决方案2】:

    首先在网络线程中获取您的 json,例如 asynchronousTask。

     DefaultHttpClient   httpclient = new DefaultHttpClient(new BasicHttpParams());
    HttpPost httppost = new HttpPost(http://someJSONUrl/jsonWebService);
    // Depends on your web service
    httppost.setHeader("Content-type", "application/json");
    
    InputStream inputStream = null;
    String result = null;
    try {
    HttpResponse response = httpclient.execute(httppost);           
    HttpEntity entity = response.getEntity();
    
    inputStream = entity.getContent();
    // json is UTF-8 by default
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
    StringBuilder sb = new StringBuilder();
    
    String line = null;
    while ((line = reader.readLine()) != null)
    {
        sb.append(line + "\n");
    }
    result = sb.toString();
    } catch (Exception e) { 
    // Oops
    }
    finally {
    try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
    } 
    

    然后像这样解析它

    try {
            JSONObject jObject = new JSONObject(result);
            Log.d("username", jObject.getString("Username"));
            Toast.makeText(getApplicationContext(), jObject.getString("Username"), Toast.LENGTH_LONG).show();
            Log.d("Password", jObject.getString("Password"));
            Log.d("eventID", jObject.getString("eventID"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    

    更多信息请查看this

    【讨论】:

      【解决方案3】:

      如果没有 LogCat,很难说,但可能你正在 MainThread 上进行网络操作,而 Android 通过抛出 android.os.NetworkOnMainThreadException 来抱怨(因为它是一个阻塞操作,所以 UI 将冻结)。如果是这种情况,您可以通过在另一个线程中执行此操作来解决(例如,通过使用 AsyncTask 或外部库,如 AndroidAsyncHttp)

      【讨论】:

        猜你喜欢
        • 2021-12-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-12
        • 2021-03-20
        • 2014-03-05
        相关资源
        最近更新 更多