来自restful web服务的JSON

我使用slim框架在php中创建了一个restful web服务。 其中一个函数返回一个动态创建的多维数组,并将其编码为JSON数组,如下所示</ p>

  [{
“hid”:100001,
“SubTable”:“ grpsubs“,
”“StatTable”:“grpstats”,
“uid”:2,
“状态”:“G”
},
{
“”hid“:100002,
”SubTable“ :“gtmsubs”,
“StatTable”:“gtmstats”,
“uid”:2,
“状态”:“R”
}]
</ code> </ pre>

在我的Android应用程序中,我使用loopj框架来获取这样的restful输出</ p>

  AsyncHttpClient client = new AsyncHttpClient(); 
client.addHeader(“Authorization”, key);
client.post(“https://mythic-beanbag-106723.appspot.com/v1/mine”,params,new AsyncHttpResponseHandler(){
//当REST返回的响应有Http响应代码时' 200'
@Override
public void onSuccess(字符串响应){
//隐藏进度对话框
hospDialog.hide();
Log.e(“响应”,响应);
尝试{

JSONArray array = new JSONArray(response);
Lo ge(“array”,String.valueOf(array.length()));

}} catch(JSONException e){
// TODO自动生成的catch块
Toast.makeText(getApplicationContext(),“ 发生错误[服务器的JSON响应可能无效]!“,Toast.LENGTH_LONG).show();
e.printStackTrace();

}
}
</ code> </ pre>

在chrome中使用高级REST客户端我可以在我的应用程序中看到JSON,当我尝试在控制台中输出JSON Log.e(“Response”,response); </ code>时显示 作为空数组 [] </ code>。 这段代码适用于我的登录功能和PHP,如果不使用动态创建的数组,我使用静态数组,如 array(“abc”=&gt; array(“def”=&gt;“ghi”),“jkl “=&gt;数组(”mno“=&gt;”pqr“))</ code>上面的代码确实输出了JSON数组。</ p>

UPDATE:</ p>
\ n

params </ p>

  RequestParams params = new RequestParams(); 
params.put(“uid”,prefs.getInt(“uid”,0));
</ code> </ pre>
</ div>

展开原文

原文

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

douzhao5656
douzhao5656 大!如果可以,请提出我的意见!:)
接近 5 年之前 回复
douzhanyan5015
douzhanyan5015 固定的
接近 5 年之前 回复
doumu5662
doumu5662 我正在查看您正在使用的API的文档。它没有指定使用AsyncHttpClient()的任何内容.post()将返回您期望的JSON响应。尝试将其更改为AsyncHttpClient()。get()。
接近 5 年之前 回复
download1214
download1214 我在REST控制台和函数的PHP代码中使用post
接近 5 年之前 回复
douhuiwan5141
douhuiwan5141 你了解POST和GET之间的区别吗?在REST控制台上你使用POST或GET吗?你的params对象中还有什么?
接近 5 年之前 回复

1个回答

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

}

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问