dtkmejg127475 2015-10-30 17:35
浏览 72

来自restful web服务的JSON

I created a restful web service in php using the slim framework. One of the functions returns a dynamically created multidimensional array and encodes it as a JSON array like this

[{  
    "hid":100001,
    "SubTable":"grpsubs",
    "StatTable":"grpstats",
    "uid":2,
    "Status":"G"
},
{  
    "hid":100002,
    "SubTable":"gtmsubs",
    "StatTable":"gtmstats",
    "uid":2,
    "Status":"R"
}]

In my android app I use the loopj framework to get the restful output like this

AsyncHttpClient client = new AsyncHttpClient();
client.addHeader("Authorization", key);
client.post("https://mythic-beanbag-106723.appspot.com/v1/mine", params, new AsyncHttpResponseHandler() {
    // When the response returned by REST has Http response code '200'
    @Override
    public void onSuccess(String response) {
        // Hide Progress Dialog
        hospDialog.hide();
        Log.e("Response", response);
        try {

            JSONArray array = new JSONArray(response);
            Log.e("array", String.valueOf(array.length()));

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            Toast.makeText(getApplicationContext(), "Error Occurred [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
            e.printStackTrace();

        }
    }

Using the Advanced REST Client in chrome I can see the JSON however in my app when I try outputting the JSON in the console Log.e("Response", response); it shows up as an empty array []. This code works for my Login function and in php if instead of using a dynamically created array I use a static array like array("abc"=>array("def"=>"ghi"), "jkl"=>array("mno"=>"pqr")) the above code does output the JSON array.

UPDATE:

params

RequestParams params = new RequestParams();
params.put("uid", prefs.getInt("uid", 0));
  • 写回答

1条回答

  • dsm0688 2015-10-30 17:54
    关注
        public class MenuTop extends Activity  {
    
    ArrayList<MenuTopJson> actorsList;
    ArrayList<String> id = new ArrayList<String>();
    ArrayList<String> onvan = new ArrayList<String>();
    ArrayList<String> sath = new ArrayList<String>();
    ArrayList<String> zir = new ArrayList<String>();
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.menutop);
        //this.setTitle("Int");
         actorsList = new ArrayList<MenuTopJson>();
        new JSONAsyncTask().execute("https://your web");        
    }
    
    
    class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
    
        ProgressDialog dialog;
    
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog = new ProgressDialog(MenuTop.this);
            dialog.setMessage("Loading, please wait");
            dialog.setTitle("Connecting server");
            dialog.show();
            dialog.setCancelable(false);
        }
    
        @Override
        protected Boolean doInBackground(String... urls) {
            try {
    
                //------------------>>
                HttpGet httppost = new HttpGet(urls[0]);
                HttpClient httpclient = new DefaultHttpClient();
                HttpResponse response = httpclient.execute(httppost);
    
                // StatusLine stat = response.getStatusLine();
                int status = response.getStatusLine().getStatusCode();
    
                if (status == 200) {
                    HttpEntity entity = response.getEntity();
                    String data = EntityUtils.toString(entity);
    
    
                    JSONObject jsono = new JSONObject(data);
                    JSONArray jarray = jsono.getJSONArray("worldpopulation");
                    //db.execSQL("DROP TABLE IF EXISTS '" + CountriesDbAdapter.SQLITE_TABLE + "'");
    
    
    
    
                    for (int i = 0; i < jarray.length(); i++) {
                        JSONObject object = jarray.getJSONObject(i);
    
                        MenuTopJson actor = new MenuTopJson();
    
                        actor.setId(object.getString("id"));
                        actor.setOnvan(object.getString("onvan"));
                        actor.setSath(object.getString("sath"));
                        actor.setZir(object.getString("zir"));
                      // Log.d("sss",object.getString("onvan").toString());
                        id.add(object.getString("id").toString());
                        onvan.add(object.getString("onvan").toString());
                        sath.add(object.getString("sath").toString());
                        zir.add(object.getString("zir").toString());
    
    
                        actorsList.add(actor);
                    }
    
                    return true;
                }
    
                //------------------>>
    
            } catch (ParseException e1) {
                e1.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return false;
        }
    
        protected void onPostExecute(Boolean result) {
            dialog.cancel();
            if(result == true)
            {
            //  Onsql();
                //Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
            //  clearApplicationData();
    
                Log.d("array=",Arrays.toString(actorsList.toArray()));
    
                final LinearLayout lm = (LinearLayout) findViewById(R.id.dynamically_create_view_element);
    
                // create the layout params that will be used to define how your
                // button will be displayed
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                        LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
              //  params.height=40;
                params.width=200;
                Log.d("array=",String.valueOf(onvan.size()));
                //Create four 
                for(int j=1;j<=onvan.size();j++) 
                {   
                    // Create LinearLayout
                    LinearLayout ll = new LinearLayout(MenuTop.this);
                    ll.setOrientation(LinearLayout.HORIZONTAL);
    
                /*    // Create TextView
                    TextView product = new TextView(this);
                    product.setText(" Product"+j+"    ");
                    ll.addView(product);
    
                    // Create TextView
                    TextView price = new TextView(this);
                    price.setText("  $"+j+"     ");
                    ll.addView(price);*/
    
                    // Create Button
                    final Button btn = new Button(MenuTop.this);
                        // Give button an ID
                        btn.setId(j+1);
                       // btn.setText("Add To Cart");
                      //  btn.setTextAppearance(this,  R.style.btnStyleShakespeare);
    
                        //btnStyleShakespeare
                        // set the layoutParams on the button
                        btn.setLayoutParams(params);
    
                        btn.setText(onvan.get(j-1).toString());
    
                        final int index = j;
                        // Set click listener for button
                        btn.setOnClickListener(new OnClickListener() {
                            public void onClick(View v) {
    
    
    
    
                                String id_list=id.get(index-1).toString();
                                String onvan_list=onvan.get(index-1).toString();
                                String sath_list=sath.get(index-1).toString();
                                String zir_list=zir.get(index-1).toString();
    
    
                                Log.i("TAG", "index :"   + id_list +":"+onvan_list+":"+sath_list+":"+zir_list);
    
                              /*  Toast.makeText(getApplicationContext(), 
                                  "Clicked:" +"index :" + id_list +":"+onvan_list+":"+sath_list+":"+zir_list, 
                                        Toast.LENGTH_SHORT).show();*/
    
    
    
                              Intent intent = new Intent(MenuTop.this, MenuTopZone1.class);
                              intent.putExtra("key1",id_list);
                              intent.putExtra("key2", onvan_list);
                              intent.putExtra("key3", sath_list);
                              intent.putExtra("key4", zir_list);
                              startActivity(intent);
                              finish();
    
                            }
                        });
    
                       //Add button to LinearLayout
                        ll.addView(btn);
                       //Add button to LinearLayout defined in XML
                        lm.addView(ll);  
                }
    
    
            }else
            {
                //clearApplicationData();
                //
                 //SQLiteDatabase.deleteDatabase("World");
                // clearApplicationData();
            }
        }
    
    
    
    }
    

    }

    in actor class: package com.wingnity.jmajid;

    public class Actors {

    private String  id;
    private String  shdaneshjo;
    private String  moavenat;
    private String  darkhast;
    private String  startdate;
    private String  taiid;
    

    // private String reshteh; private String tozih;

    public Actors() {
        // TODO Auto-generated constructor stub
    }
    
    public Actors(
            String id,
            String shdaneshjo,
            String moavenat,
            String darkhast,
            String startdate,
            String taiid,
            //String reshteh,
            String tozih
            ) {
        super();
    
        this.id=id;
        this.shdaneshjo=shdaneshjo;
        this.moavenat=moavenat;
        this.darkhast=darkhast;
        this.startdate=startdate;
        this.taiid=taiid;
        //this.reshteh=reshteh;
        this.tozih=tozih;
    
    
    }
    
    
    public String getId() {
        return id;
    }
    
    public void setId(String id) {
        this.id = id;
    }
    
    public String getShdaneshjo() {
        return shdaneshjo;
    }
    
    public void setShdaneshjo(String shdaneshjo) {
        this.shdaneshjo = shdaneshjo;
    }
    
    public String getMoavenat() {
        return moavenat;
    }
    
    public void setMoavenat(String moavenat) {
        this.moavenat = moavenat;
    }
    
    public String getDarkhast() {
        return darkhast;
    }
    
    public void setDarkhast(String darkhast) {
        this.darkhast = darkhast;
    }
    public String getStartdate() {
        return startdate;
    }
    
    public void setStartdate(String startdate) {
        this.startdate = startdate;
    }
    
    public String getTaiid() {
        return taiid;
    }
    
    public void setTaiid(String taiid) {
        this.taiid = taiid;
    }
    
    public String getTozih() {
        return tozih;
    }
    
    public void setTozih(String tozih) {
        this.tozih = tozih;
    }
    

    }

    评论

报告相同问题?

悬赏问题

  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 C#调用python代码(python带有库)
  • ¥15 矩阵加法的规则是两个矩阵中对应位置的数的绝对值进行加和
  • ¥15 活动选择题。最多可以参加几个项目?
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)
  • ¥20 怎么在stm32门禁成品上增加查询记录功能
  • ¥15 Source insight编写代码后使用CCS5.2版本import之后,代码跳到注释行里面