Android上的Symfony 3 JSONResponse

时间:2016-05-01 16:00:09

标签: php android json symfony

所以即时使用createQuery连接我的symfony数据库与Doctrine这样

// JSON ACTION
public function jsonAction()
{
$em = $this->getDoctrine()->getEntityManager();
$query = $em->createQuery('SELECT pa FROM CBMedBundle:Patients pa');
$myArray = $query->getArrayResult();
return new JsonResponse($myArray);
}

在网址:http://localhost/Symfony/web/app_dev.php/json 现在我想在Android(eclipse android)上导出结果(jsonreponse)并在那里显示响应! 我怎么能这样做?

我在谷歌上发现这个代码,关于在Android上显示json代码,但我不知道如何根据我的问题调整它。感谢

    public class MainActivity extends Activity {
        TextView t;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            t = (TextView) findViewById(R.id.text1);
         StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
         StrictMode.setThreadPolicy(policy);
         t.setText(getServerData(strURL));
        }
         public static final String strURL = "http://10.0.2.2/connexion.php";

         private String getServerData(String returnString) {
             InputStream is = null;
             String result ="";

             ArrayList<NameValuePair> nameValuePaires = new ArrayList<NameValuePair>();
             nameValuePaires.add(new BasicNameValuePair("tblville","tblville"));
             // Envoie de la commande Http
             try{
                 HttpClient httpclient = new DefaultHttpClient();
                 HttpPost httppost = new HttpPost(strURL);
                 httppost.setEntity(new UrlEncodedFormEntity(nameValuePaires));
                 HttpResponse response = httpclient.execute(httppost);
                 HttpEntity entity = response.getEntity();
                 is = entity.getContent();
         }
         catch(Exception e){
          Log.e("log_tag","Error in http connection "+e.toString());
           }


         //conversion de la réponse en chaine de caractère
            try
            {
             BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));

             StringBuilder sb  = new StringBuilder();

             String line = null;

             while ((line = reader.readLine()) != null) 
             {
                  sb.append(line + "\n");
             }

             is.close();

             result = sb.toString();
            }
            catch(Exception e)
            {
             Log.e("log_tag","Error converting result"+e.toString());
            }
            //recuperation des donnees json
            try{
              JSONArray jArray = new JSONArray(result);

                 for(int i=0;i<jArray.length();i++)
                 {

                       JSONObject json_data = jArray.getJSONObject(i);
                       Log.i("log_tag","ID_ville : "+json_data.getString("ID_ville")+" , Nom_ville : "+json_data.getString("Nom_ville")
                               );
                        returnString += "\n\t" + jArray.getJSONObject(i);

                }
            }
                catch(JSONException e){
                 Log.e("log_tag","Error Parsing data"+e.toString());
                } 
                return returnString;

    }
    }

编辑:JSONresponse结果

[{"id":1,"nom":"Kane","prenom":"Samba","DateNaissance":{"date":"1995-03-08     00:00:00","timezone_type":3,"timezone":"Europe\/Paris"},"LieudeNaissance":"Nouakchott","sexe":"Homme","adresse":"Tunis","profession":"Etudiant","NumerodeTel":"+21629760962","Email":"kane_samba4@yahoo.fr","SituationFamilial":"Mari\u00e9"},{"id":2,"nom":"Bebeskho","prenom":"AllStar","DateNaissance":{"date":"1995-02-08 00:00:00","timezone_type":3,"timezone":"Europe\/Paris"},"LieudeNaissance":"Bamako","sexe":"Homme","adresse":"Tunis","profession":"Cuisinier","NumerodeTel":"+2167583486","Email":"bebeskho@gmail.com","SituationFamilial":"C\u00e9libataire"},{"id":3,"nom":"Vecenzo","prenom":"Gaimno","DateNaissance":{"date":"1995-01-01 00:00:00","timezone_type":3,"timezone":"Europe\/Paris"},"LieudeNaissance":"Tunis","sexe":"Homme","adresse":"Ariana","profession":"Etudiant","NumerodeTel":"+21654758","Email":"vecenzogo","SituationFamilial":"Mari\u00e9"},{"id":4,"nom":"Diara","prenom":"Bakary","DateNaissance":{"date":"1995-06-10 00:00:00","timezone_type":3,"timezone":"Europe\/Paris"},"LieudeNaissance":"Dakar","sexe":"Homme","adresse":"Dakar Sacr\u00e9 Coeur","profession":"Etudiant","NumerodeTel":"+2214753526","Email":"diaBakis@gmail.com","SituationFamilial":"C\u00e9libataire"}]

JsonResponse Image

现在,我只想在我的Android模拟器应用程序(eclipse)上显示此结果

1 个答案:

答案 0 :(得分:1)

要根据您的需要调整代码 - 您需要更改URL以指向您的服务器。将test rax, 2049更改为public static final String strURL = "http://10.0.2.2/connexion.php";(我假设HTTP-GET请求返回您粘贴的JSON数组)。然后,您可以修改JSON处理代码以提取JSON文件中包含的详细信息 - 如下所示:

http://<your-server-ip-address>/Symfony/web/app_dev.php/json

但我真的建议您使用像Gson这样的东西将传入的JSON有效负载解析为&#34; Person&#34;例如,对象。作为一个例子,假设你已经创建了一个Person类,你可以这样做:

for(int i=0;i<jArray.length();i++) { JSONObject personJSONData= jArray.getJSONObject(i); String id = personJSONData.getString("id"); String nom = personJSONData.getString("nom"); //do the same for the other attributes //note that according to your JSON file, DateNaissance is a JSONObject - so you have to do something like JSONObject dateNaissanceObject = personJSONData.getJSONObject("DateNaissance"); } Here就是一个很好的例子 - here是另一个使用Gson的好例子 - 那里也是一个很好的教程here