在android中为我的格式解析json web服务

时间:2013-02-28 11:22:55

标签: android json

我正在开发一个简单的登录应用程序。我的JSON Web服务返回用户名。这是JSON代码的格式:

[{"demologin":{"username":"demoname","id":100}}]

这是我的代码:

private class LongRunningGetIO extends AsyncTask <Void, Void, String> {

    protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException {
       InputStream in = entity.getContent();
         StringBuffer out = new StringBuffer();
         int n = 1;
         while (n>0) {
             byte[] b = new byte[4096];
             n =  in.read(b);
             if (n>0) out.append(new String(b, 0, n));
         }
         return out.toString();
    }

    protected String doInBackground(Void... params) {
         HttpClient httpClient = new DefaultHttpClient();
         HttpContext localContext = new BasicHttpContext();

         username=txtUserName.getText().toString();
         password=txtPassword.getText().toString();



         String url="MY URL HERE";
         HttpGet httpGet = new HttpGet(url);

         String text = null;
         String result = null;
         String webusername=null;
         int webuserid;
         ArrayList<String> desc=new ArrayList<String>();

         try {

               HttpResponse response = httpClient.execute(httpGet, localContext);
               HttpEntity entity = response.getEntity();
               text = getASCIIContentFromEntity(entity);



                   JSONArray ja = new JSONArray(text) ;
                   // ITERATE THROUGH AND RETRIEVE CLUB FIELDS
                                int n = ja.length();
                                for (int i = 0; i < n; i++) {
                                    // GET INDIVIDUAL JSON OBJECT FROM JSON ARRAY
                                 JSONObject jo = ja.getJSONObject(i);

                                 webusername= jo.getString("demologin");
                                 webuserid= jo.getInt("id");

                                }
         } catch (Exception e) {



                   e.getLocalizedMessage();
                   }    
         return webusername; 
    }   
    protected void onPostExecute(String results) {
        if (results!=null) {

            String sendusername=results;
            Intent inte=new Intent(Login.this,FrontPage.class);
            inte.putExtra("displayusername", sendusername);
            startActivity(inte);


        }
        else
            Toast.makeText(getApplicationContext(), "Invalid user", Toast.LENGTH_LONG).show();


        }
}

这里的问题是我不知道如何将用户名变成字符串并通过网络传递。有没有人知道如何做到这一点?

1 个答案:

答案 0 :(得分:0)

我认为这篇文章会对你有所帮助,这里的字符串操作是在从wsdl返回的字符串上完成的,你可以使用相同的字符串拆分函数来分割你的结果 process an array returned by web service