来自restful Web服务的JSON

时间:2015-10-30 17:35:34

标签: php android json slim loopj

我使用slim框架在php中创建了一个restful web服务。其中一个函数返回一个动态创建的多维数组,并将其编码为像这样的JSON数组

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

在我的Android应用程序中,我使用loopj框架来获得像这样的

的宁静输出
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();

        }
    }

在chrome中使用高级REST客户端我可以在我的应用程序中看到JSON,当我尝试在控制台Log.e("Response", response);中输出JSON时,它显示为空数组[]。这段代码适用于我的Login函数和php,如果不使用动态创建的数组,我使用像array("abc"=>array("def"=>"ghi"), "jkl"=>array("mno"=>"pqr"))这样的静态数组,上面的代码会输出JSON数组。

更新:

PARAMS

RequestParams params = new RequestParams();
params.put("uid", prefs.getInt("uid", 0));

1 个答案:

答案 0 :(得分:0)

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



}

}

在actor类中:           包com.wingnity.jmajid;

公共类演员{

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

}