簡體   English   中英

如何在Android中使用逗號解析JSON?

[英]How can I parse JSON with comma in android?

我試圖解析JSON,我的代碼無法使用一個URL,而可以使用其他URL。 我認為這是有問題的昏迷,但我不確定,因此請查看我的代碼和幫助。 我試圖用循環中的點替換昏迷,但我得到的是JSON異常。 而且,當我更改URL時,也不例外。 令人困惑的...這是行不通的URL: http : //api.hnb.hr/tecajn/v1這是我測試過的並且可以正常工作: https : //newsapi.org/v2/top-headlines?country=us&category = business&apiKey = e402c76fc8584a1c81849179f1277a74在更改URL的同時,我也更改了數據,因此它不是書面問題。

這是我的昏迷替換代碼:

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

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

    return sb.toString();
}

另一部分是URL和JSONArray:

    @Override
    protected Void doInBackground(Void... arg0) {
        URLconnection urlConn = new URLconnection();
        // Making a request to url and getting response
        String url = "http://api.hnb.hr/tecajn/v1";
        //.........connection.........
        String response = urlConn.makeServiceCall(url);

        Log.e(TAG, "Response from url: " + response);
        if (response != null) {
            try {
                JSONObject jsonObj = new JSONObject(response);

                // Getting JSON Array node
                arr = jsonObj.getJSONArray("values");

                for (int i = 0; i < article.length(); i++) {

                    JSONObject c = arr.getJSONObject(i);
                    header = c.getString("Valuta");

               }

            } catch (final JSONException e) {
                Log.e(TAG, "Json parsing error.");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Json parsing error: 216",
                                Toast.LENGTH_LONG).show();
                    }
                });
            }

逗號不是問題。 這是第一個角色。 一個是方括號,另一個是花括號。

因此,您需要將第一個響應解析為數組而不是對象

new JSONArray(response);

話雖這么說,所以您不能對兩個URL使用相同的方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM