java - 如何访问从android中的restful web服务传递的json数组?

标签 java android json rest arrays

我已经成功创建了一个rest web服务,它返回有两个字段的jsonarray 来自数据库的 ID 和城市。

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

我只需要将这些值放入微调器中...

我的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();
        }

    }
}

最佳答案

最好创建 Model 类,然后您可以使用 gson 解析响应。

例如,

假设您的回复包含两个字符串“名称”和“邮件”。创建一个带有两个字符串的模型。

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

然后使用 gson 解析您的响应。

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

然后就可以访问对象sample的成员了。根据需要更改 Sample 类(使用字符串和 int 数组。您可以使用 ArrayList 而不是 Array)

关于java - 如何访问从android中的restful web服务传递的json数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24141743/

相关文章:

json - antd 时间线的 Reactjs 条件属性

javascript - 如何从 JavaScript 对象生成校验和?

c# - 具有数字成员的 Json 对象未绑定(bind)到 MVC Controller 中的 Object.IntegerProperty

java - 如何从oracle过程中获取java中对象类型解析的数组

java - 如何在2个不同类型的列表中查找元素匹配并使用java 8流连接它们?

java - 什么是 NullPointerException,我该如何解决?

android - 重新安装后的 Google Drive Application Data 文件夹

android - Unity Android 应用程序上的 Facebook API,登录时说它是 "cancelled by the Player"?

java - 转置 NxN 矩阵

android - 无法将 AndroidManifest.xml 文件迁移到 Android Studio?