如何从URL获取数组中的数据

时间:2013-11-23 04:57:48

标签: java android json android-asynctask

我正在尝试从JSON URL获取数据。当然是通过AsyncTask。但问题是JSON文件没有Object。这是一个数组。 JSON URLapi website

有人能告诉我如何为这个JSON文件创建JSONArray和JSONObject吗?!

以下是我所做的使应用程序停止工作的原因

//URL to get JSON Array
private static String url = "http://api.worldbank.org/countries/ir?format=json";

//JSON Node Names 
private static final String TAG_OBJ = "user";
private static final String NAME = "name";
private static final String CAPITALCITY = "capitalCity";
    .
    .
    .
    class GetJSONTask extends AsyncTask<String, Void, JSONObject> {


    protected JSONObject doInBackground(String... urls) {
        // Creating new JSON Parser
        JSONParser jParser = new JSONParser();

        // Getting JSON from URL
        JSONObject json = JSONParser.getJson(url);

        return json;
    }
    protected void onPostExecute(JSONObject json) {
        //Getting JSON Array
        try {
            user = json.getJSONArray(TAG_OBJ);
            JSONObject c = user.getJSONObject(0);

            //Stroing JSON item in a Variable
            String name = c.getString(NAME);
            String capitalCity = c.getString(CAPITALCITY);

            //Importing TextView
            final TextView view1 = (TextView)findViewById(R.id.name);
            final TextView view2 = (TextView)findViewById(R.id.capitalCity);

            //Set JSON Data in TextView
            view1.setText(name);
            view2.setText(capitalCity);

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

    }
}

4 个答案:

答案 0 :(得分:0)

if(i<jArray.length()) {
         JSONObject json_obj = jArray.getJSONObject(i);   //get array object
         name = json_obj.getString("your tag name");        fetch item here
    }

答案 1 :(得分:0)

使用JSON数组。这是我的代码: -

String url = "http://api.androidhive.info/contacts/";
    JSONParser jParser = new JSONParser();

    // Getting JSON from URL
    JSONObject json = jParser.getJSONFromUrl(url);
    try {
        // Getting JSON Array
        JSONArray begin = json.getJSONArray("contacts");
        JSONObject c = begin.getJSONObject(0);

        // Storing  JSON item in a Variable
        String id = c.getString("id");
        String name = c.getString("name");
        String size = c.getString("email");

将此放入您的异步

答案 2 :(得分:0)

如下所示更改您的MainActivity.java,

public class MainActivity extends Activity {

// URL to get JSON Array
private static String url = "http://api.worldbank.org/countries/ir?format=json";

// JSON Node Names
private static final String TAG_NAME = "name";
private static final String TAG_CAP_City = "capitalCity";
JSONArray responseArray = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    new GetJSONTask().execute();



}
class GetJSONTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... arg0) {
        // Creating new JSON Parser
        JSONParser jParser = new JSONParser();

        // Getting JSON from URL
        String json = jParser.getJSONFromUrl(url);
        return json;
    }
    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);

        try {
            // Getting JSON Array
            responseArray = new JSONArray(result);
            JSONArray parsedArray=responseArray.getJSONArray(1);
            JSONObject c = parsedArray.getJSONObject(0);

            // Storing JSON item in a Variable
            String name = c.getString(TAG_NAME);
            String email = c.getString(TAG_CAP_City);

            // Importing TextView
            // final TextView uid = (TextView)findViewById(R.id.uid);
            final TextView name1 = (TextView) findViewById(R.id.name);
            final TextView email1 = (TextView) findViewById(R.id.email);

            // Set JSON Data in TextView
            // uid.setText(id);
            name1.setText(name);
            email1.setText(email);

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

}

}

同时更改JSONParser.java

public class JSONParser {

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

    // constructor
    public JSONParser() {

    }

    public String 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 JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }*/

        // return JSON String
        return json;

    }
}

答案 3 :(得分:0)

请注意我使用了严格政策。您继续使用Async Task并将我的代码放在那里。这是我的与您的要求相关的准则。

JsonParser.Java

    package com.example.test;

import android.os.StrictMode;
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 JSONObject jObj = null;
static String json = "";
static JSONArray jArray = null;
// constructor
public JSONParser() {

}

public JSONArray getJSONFromUrl(String url) {

    // Making HTTP request
    try {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

        StrictMode.setThreadPolicy(policy);
        // 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 {
        jArray = new JSONArray(json);
     //   jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jArray;

}
}

MainActivity.java

        package com.example.test;

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

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 android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;

public class MainActivity extends Activity {
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Making HTTP request
        String url = "http://api.worldbank.org/countries/ir?format=json";
        JSONParser jParser = new JSONParser();

        // Getting JSON from URL
        JSONArray json = jParser.getJSONFromUrl(url);
        try {
            JSONArray json2 = json.getJSONArray(1); // Your second Array in your json

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

                JSONObject c = json2.getJSONObject(i);
                // Storing  JSON item in a Variable
                String name = c.optString("name","");
                String capitalCity = c.optString("capitalCity","");

            }

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


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}