Android JSON从URL解析

Geo*_*rge 0 android json

我正在尝试在Android中执行JSON项目.这是我的代码.

由于某种原因,数据在运行时不会显示在TextBox中.我不确定我错在哪里.

这是我试图获取数据的网址:http://cocoalabs.in/demo/ego/index.php/home/read_all_users

我试图抓住4个字符串并将它们显示给TextViews

这是我的代码:

MainActivity.Java

public class MainActivity extends Activity
{

static String CocoaInfo="http://cocoalabs.in/demo/ego/index.php/home/read_all_users";
static String clfName = "";
static String cllName = "";
static String clLocation = "";
static String clPh1 = "";


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

    //To perform background tasks, like grabbing info from website and write it to GUI
    new MyAsyncTask().execute();
}

public class MyAsyncTask extends AsyncTask<String, String, String>
{

    @Override
    protected String doInBackground(String... strings)
    {
        /*Get HTTP client that scores streaming uploads & Downloads
        Here download RESTful information from CocoaLabs URL*/
        DefaultHttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());

        /*Use POST method to grab from data from URL*/
        HttpPost httpPost = new HttpPost(CocoaInfo);

        /*Define type of service we're using - JSON service*/
        httpPost.setHeader("Content-type", "application/json");

        /*To Read data from URL*/
        InputStream inputStream = null;

        /*To hold all the data we get from URL*/
        String result = null;

        try
        {
            /*Asking for a response from the web service*/
            HttpResponse response = httpClient.execute(httpPost);

            /*Has the content from URL along with header and other info*/
            HttpEntity entity = response.getEntity();

            /*Get the main content from the URL*/
            inputStream = entity.getContent();

            /*Read data from the stream until buffer is full. Helps to grab in bunch*/
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"),8);

            /*Creating StringBuilder to store the read data*/
            StringBuilder theStringBuilder = new StringBuilder();

            /*For storing the read line*/
            String line = null;

            /*Read all the data from buffer until nothing is left*/
            while((line = reader.readLine())!=null)
            {
                /*Append each line to the Builder object*/
                theStringBuilder.append(line + "\n");
            }

            /*After finishing reading all the data*/
            result = theStringBuilder.toString();

        }

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

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

        finally
        {
            try
            {
                /*Close the InputStream*/
                if (inputStream!=null)
                    inputStream.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }

        /*Create JSON object to hold a bunch of key-value pairs from the JSON source*/
        JSONObject jsonObject;

        /*To print all the information we downloaded in the LogCat for debugging*/
        Log.v("JSONParser RESULT ", result);


        try
        {
            /*Get the JSON object with all the data*/
            jsonObject = new JSONObject(result);

            clfName = jsonObject.getString("fname");
            cllName = jsonObject.getString("lname");
            clLocation = jsonObject.getString("location");
            clPh1 = jsonObject.getString("ph1");

            Log.v("JSONParser RESULT", clfName);
            Log.v("JSONParser RESULT", cllName);
            Log.v("JSONParser RESULT", clLocation);
            Log.v("JSONParser RESULT", clPh1);

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

        return result;

    }

    //This method is called after all background tasks are done
    /*Writes all the information to the TextViews layout*/
    @Override
    protected void onPostExecute(String result)
    {
        /*Find the buttons on the screen*/
        TextView fNameTV = (TextView) findViewById(R.id.fNameTV);
        TextView lNameTV = (TextView) findViewById(R.id.lNameTV);
        TextView locationTV = (TextView) findViewById(R.id.locationTV);
        TextView ph1TV = (TextView) findViewById(R.id.ph1TV);

        /*Change the value to be displayed on TextViews*/
        fNameTV.setText("First Name is" +clfName);
        lNameTV.setText("Last Name is" +cllName);
        locationTV.setText("Location is" +clLocation);
        ph1TV.setText("Phone Number is" +clPh1);

    }
}
Run Code Online (Sandbox Code Playgroud)

}

Ped*_*ira 5

那是因为给定的json是一个数组而不是一个对象.

您需要先将if转换为数组并迭代它:

JSONArray myArray = new JSONArray(result);
Run Code Online (Sandbox Code Playgroud)

代替

jsonObject = new JSONObject(result);
Run Code Online (Sandbox Code Playgroud)

要迭代数组,应该这样做:

  for( i=0;i<myArray.length();i++){
    JSONObject anObjectOfTheArray= myArray.getJSONObject(i);
    Log.v("CONTENT",anObjectOfTheArray.getString("uname"));
   }
Run Code Online (Sandbox Code Playgroud)