【问题标题】:Symfony 3 JSONResponse on AndroidAndroid 上的 Symfony 3 JSONResponse
【发布时间】:2016-05-01 16:00:08
【问题描述】:

所以我使用 createQuery 连接到我的 symfony 数据库,像这样

// 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) 并在那里显示响应! 我该怎么做?

我在 google 上找到了这段代码,关于在 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;

    }
    }

编辑:JSON 响应结果

[{"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) 上显示这个结果

【问题讨论】:

  • 你能粘贴你的服务器生成的 JSON 响应吗?您可能希望在您的 Android 代码中解析此 JSON - 因此它将帮助我们了解它的外观并为您提供建议。

标签: php android json symfony


【解决方案1】:

要根据您的目的调整代码 - 您需要更改 URL 以指向您的服务器。将public static final String strURL = "http://10.0.2.2/connexion.php"; 更改为http://&lt;your-server-ip-address&gt;/Symfony/web/app_dev.php/json 之类的东西(我假设HTTP-GET 请求返回您粘贴的JSON 数组)。然后修改 JSON 处理代码以提取 JSON 文件中包含的详细信息 - 如下所示:

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

 }

但我真的建议您使用 Gson 之类的工具将传入的 JSON 有效负载解析为“Person”对象列表,例如。举个例子,假设你已经创建了一个 Person 类,你会这样做:

List&lt;Person&gt; persons = gson.fromJson(result, new TypeToken&lt;List&lt;Person&gt;&gt;(){}.getType()); . Here 是一个很好的例子 - here 是另一个使用 Gson 的好例子 - 还有一个很好的教程 here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-07
    • 2017-02-25
    • 1970-01-01
    • 2018-10-23
    • 1970-01-01
    • 2017-10-18
    • 1970-01-01
    相关资源
    最近更新 更多