简体   繁体   中英

JSON data Parsing Android Studio

I am currently a beginner to android programming and right now I am developing an app to make a JSON connection to a server and display the JSON data. The connection is currently successfully being made however I am having problems displaying the JSON data on my app. My JSON data come in the following format`

I was firstly using JSONObject instead of JSONArrays in places which i realised were incorrect so I think I have changed these correctly however in my MainActivity I am now confused at how to display the data from the JSON connection on my app. Any help here would be appreciated. My current error appears in the MainActivity where all three of the Node_ are.

Error:(46, 25) error: method getJSONArray in class JSONArray cannot be applied to given types; required: int found: String reason: actual argument String cannot be converted to int by method invocation conversion

I will also include my classes below:

MainActivity Class

    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 Class

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;
    }
}

Your issue is here.

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

Your first tag is JSONArray and in JSONParser class you have returned with JSONArray . So just remove this line

array = json.getJSONArray(Node_BusinessName);

and use like

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

NOTE : You'r performing your network related operations on your main thread which is not recommended way. So use AsyncTask or Thread .

First, i think that your json text is corrupted. If the the problem is about converting data, you can get it as a string or an object, after that convert it using java code.

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);
}

Try this.

And try to put this JSON code in Async Task that will be more effective.

Try to follow this link . You will learn more.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM