簡體   English   中英

JSON數據解析Android Studio

[英]JSON data Parsing Android Studio

我目前是android編程的初學者,現在我正在開發一個應用程序,以建立與服務器的JSON連接並顯示JSON數據。 目前已成功建立連接,但是在我的應用程序上顯示JSON數據時遇到問題。 我的JSON數據采用以下格式`

我首先在我意識到不正確的地方使用JSONObject而不是JSONArrays,所以我認為我已經正確更改了這些,但是現在在MainActivity中,我對如何在應用程序上顯示來自JSON連接的數據感到困惑。 在這里的任何幫助,將不勝感激。 我當前的錯誤出現在所有三個Node_所在的MainActivity中。

錯誤:(46,25)錯誤:類JSONArray中的方法getJSONArray無法應用於給定類型; 必需:找到的整數:字符串原因:實際參數字符串不能通過方法調用轉換轉換為整數

我還將在下面包括我的課程:

MainActivity類

    import android.os.StrictMode;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

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


public class MainActivity extends ActionBarActivity {



    //URL to get JSON Array
    private static String url = "";

    //JSON Node Names
    private static final String Node_ID = "id";
    private static final String Node_BusinessName = "BusinessName";

    JSONArray array = null;



    @Override
    protected void onCreate(Bundle savedInstanceState) {

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Creating new JSON Parser
        JSONParser jParser = new JSONParser();

        // Getting JSON from URL
        JSONArray json = jParser.getJSONFromUrl(url);
        try {
            // Getting JSON Array
            array = json.getJSONArray(Node_BusinessName);
            JSONArray c = array.getJSONArray(0);

            // Storing  JSON item in a Variable
            String id = c.getString(Node_ID);
            String businessName = c.getString(Node_BusinessName);


            //Importing TextView
            final TextView ID = (TextView)findViewById(R.id.ID);
            final TextView BusinessNameText = (TextView)findViewById(R.id.BusinessName);

            //Set JSON Data in TextView
            ID.setText(id);
            BusinessNameText.setText(businessName);

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

JSONParser類

import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;


public class JSONParser {

    static InputStream is = null;
    static JSONArray jObj = null;
    static String json = "";


    // constructor
    public JSONParser() {
    }
    public JSONArray getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
        // try parse the string to a JSON object
        try {
            jObj = new JSONArray(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
        // return JSON String
        return jObj;
    }
}

您的問題在這里。

JSONArray json = jParser.getJSONFromUrl(url);
 try {
       array = json.getJSONArray(Node_BusinessName);
       JSONArray c = array.getJSONArray(0);

您的第一個標簽是JSONArray並且在JSONParser類中已使用JSONArray返回。 所以只要刪除這行

array = json.getJSONArray(Node_BusinessName);

並使用像

for(int i=0; i<json.length();i++){
  JSONObject jb = json.getJSONObject(i);
  String id = jb.getString(Node_ID);
  // same for other keys
}

注意:您不建議在主線程上執行與網絡相關的操作。 因此,請使用AsyncTaskThread

首先,我認為您的json文本已損壞。 如果問題與轉換數據有關,則可以使用Java代碼將其轉換為字符串或對象后再獲取。

for (int i = 0; i < products.length(); i++) {
    JSONObject c = products.getJSONObject(i);

    // Storing each json item in variable
    String id = c.getString(TAG_PID);
    String name = c.getString(TAG_NAME);

    // creating new HashMap
    HashMap<String, String> map = new HashMap<String, String>();

    // adding each child node to HashMap key => value
    map.put(TAG_PID, id);
    map.put(TAG_NAME, name);

    // adding HashList to ArrayList
    productsList.add(map);
}

嘗試這個。

並嘗試將此JSON代碼放入Async Task中,這樣會更有效。

嘗試點擊此鏈接 您將學到更多。

暫無
暫無

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

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