简体   繁体   English

如何访问从Android中的静态Web服务传递的json数组?

[英]How to access json array that is passed from restful web service in android?

I have successfully created a rest web service and it returns jsonarray which has two fields id and city from data base. 我已经成功创建了一个rest Web服务,它返回了jsonarray,它具有两个字段id和来自数据库的city。

My resr web service is 

@GET @得到

@Path("city")

@Produces("application/json")

public String getJson() {

    PropertyPojo propojo=null;

    ArrayList cityList = new ArrayList();

    JSONArray list = new JSONArray();

     Map m1 = new LinkedHashMap();

     List  l1 = new LinkedList();

     String jsonString = null;

    try{
        cityList=PDao.CityList();
         Iterator it=cityList.iterator();

                while(it.hasNext())
                 {
                    propojo=(PropertyPojo)it.next();

                    m1.put(propojo.getKeyid(),propojo.getKeyvalue());

                 }


    }catch(Exception e){

    }
    l1.add(m1);
    jsonString = JSONValue.toJSONString(l1);
    return jsonString;
}

I just need to put these values into a spinner... 我只需要将这些值放入微调器中即可。

My android code is 我的Android代码是

public class MainActivity extends Activity {

    Spinner spinner;

    private static final String SERVICE_URL = "http://192.168.1.6:8080/eSava_RestWeb/webresources/service";

    private static final String TAG = "AndroidRESTClientActivity";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        spinner = (Spinner) findViewById(R.id.city);
    }

    public void retrieveSampleData(View vw) {

        String sampleURL = SERVICE_URL + "/city";

        WebServiceTask wst = new WebServiceTask(WebServiceTask.GET_TASK,
                this, "GETting data...");

        wst.execute(new String[] { sampleURL });

    }

    @SuppressLint("NewApi")
    public void handleResponse(String response) {

        try {
            // JSONObject jso = new JSONObject(response);
            JSONArray json = new JSONArray(response);

            ArrayList<String> list = new ArrayList<String>();
            JSONArray jsonArray = (JSONArray) json;
            if (jsonArray != null) {
                int len = jsonArray.length();
                for (int i = 0; i < len; i++) {
                    list.add(jsonArray.get(i).toString());
                }
            }

            Spinner s = (Spinner) findViewById(R.id.city);
            ArrayAdapter adapter = new ArrayAdapter(this,
                    android.R.layout.simple_spinner_item, list);
            s.setAdapter(adapter);

        } catch (Exception e) {
            Log.e(TAG, e.getLocalizedMessage(), e);
        }

    }

    private class WebServiceTask extends AsyncTask<String, Integer, String> {

        public static final int POST_TASK = 1;
        public static final int GET_TASK = 2;

        private static final String TAG = "WebServiceTask";

        // connection timeout, in milliseconds (waiting to connect)
        private static final int CONN_TIMEOUT = 3000;

        // socket timeout, in milliseconds (waiting for data)
        private static final int SOCKET_TIMEOUT = 5000;

        private int taskType = GET_TASK;
        private Context mContext = null;
        private String processMessage = "Processing...";

        private ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();

        private ProgressDialog pDlg = null;

        public WebServiceTask(int taskType, Context mContext,
                String processMessage) {

            this.taskType = taskType;
            this.mContext = mContext;
            this.processMessage = processMessage;
        }

        public void addNameValuePair(String name, String value) {

            params.add(new BasicNameValuePair(name, value));
        }

        private void showProgressDialog() {

            pDlg = new ProgressDialog(mContext);
            pDlg.setMessage(processMessage);
            pDlg.setProgressDrawable(mContext.getWallpaper());
            pDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            pDlg.setCancelable(false);
            pDlg.show();

        }

        @Override
        protected void onPreExecute() {

            showProgressDialog();

        }

        protected String doInBackground(String... urls) {

            String url = urls[0];
            String result = "";

            HttpResponse response = doResponse(url);

            if (response == null) {
                return result;
            } else {

                try {

                    result = inputStreamToString(response.getEntity()
                            .getContent());

                } catch (IllegalStateException e) {
                    Log.e(TAG, e.getLocalizedMessage(), e);

                } catch (IOException e) {
                    Log.e(TAG, e.getLocalizedMessage(), e);
                }

            }

            return result;
        }

        @Override
        protected void onPostExecute(String response) {

            JSONArray jsArray;
            // jsArray = new JSONArray(response);
            handleResponse(response);
            pDlg.dismiss();

        }

        // Establish connection and socket (data retrieval) timeouts
        private HttpParams getHttpParams() {

            HttpParams htpp = new BasicHttpParams();

            HttpConnectionParams.setConnectionTimeout(htpp, CONN_TIMEOUT);
            HttpConnectionParams.setSoTimeout(htpp, SOCKET_TIMEOUT);

            return htpp;
        }

        private HttpResponse doResponse(String url) {

            // Use our connection and data timeouts as parameters for our
            // DefaultHttpClient
            HttpClient httpclient = new DefaultHttpClient(getHttpParams());

            HttpResponse response = null;

            try {
                switch (taskType) {

                case POST_TASK:
                    HttpPost httppost = new HttpPost(url);
                    // Add parameters
                    httppost.setEntity(new UrlEncodedFormEntity(params));

                    response = httpclient.execute(httppost);
                    break;
                case GET_TASK:
                    HttpGet httpget = new HttpGet(url);
                    response = httpclient.execute(httpget);
                    break;
                }
            } catch (Exception e) {

                Log.e(TAG, e.getLocalizedMessage(), e);

            }

            return response;
        }

        private String inputStreamToString(InputStream is) {

            String line = "";
            StringBuilder total = new StringBuilder();

            // Wrap a BufferedReader around the InputStream
            BufferedReader rd = new BufferedReader(
                    new InputStreamReader(is));

            try {
                // Read response until the end
                while ((line = rd.readLine()) != null) {
                    total.append(line);
                }
            } catch (IOException e) {
                Log.e(TAG, e.getLocalizedMessage(), e);
            }

            // Return full string
            return total.toString();
        }

    }
}
String[] city= {};
String[] id= {};

JSONArray jsonDetailsObj = json.getJSONArray("cityList");
JSONObject jsonLoop = null; 
int noOfPoints = jsonDetailsObj.length();

city= new String[noOfPoints];
id= new String[noOfPoints];


for (int i=0 ; i < noOfPoints ; i++)
{
   jsonLoop=jsonDetailsObj.getJSONObject(i);
   city [i] = jsonLoop.getString("CityName");
   id[i] = jsonLoop.getString("ID");
}

Its better to create Model class and then you can parse the response with gson. 创建Model类更好,然后可以使用gson解析响应。

For example, 例如,

Imagine that you have your response with two strings Name and Mail. 想象一下,您的响应包含两个字符串Name和Mail。 Create a model with two strings. 用两个字符串创建一个模型。

public class Sample{
  public Sample()
  {

  }
  @SerializedName("Name")//if needed
  String name;
  @SerializedName("Email")//if needed
  String email;
  public void set(String name) {
        this.name = name;
    }

  public String getName() {
        return name;
    }
  public void set(String email) {
        this.email = email;
    }

  public String getEmail() {
        return email;
    }
}

Then parse your response with gson. 然后用gson解析您的回复。

Sample sample = gson.fromJson(jsonRes.toString(), Sample.class);

Then you can access the members of the object sample. 然后,您可以访问对象样本的成员。 Change the Sample class as you needed(with the array of strings and int. You can use ArrayList instead of Array) 根据需要更改Sample类(使用字符串和整数数组。可以使用ArrayList而不是Array)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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