繁体   English   中英

JSON解析android json数组和json对象

[英]JSON parsing android json arrays and json object

我通过 volley 得到一个 json 响应,响应如下:

{
   "status":"success",
   "message":"Request Successfull",
   "messagetitle":"Success",
   "show":"false",
   "goback":"false",
   "companies":[
      {
         "id":"14",
         "category":{
            "id":"1",
            "name":"test"
         },
         "subcategory":{
            "id":"1",
            "name":"test",
            "image":"https:\/\/page.com\/page\/uploads\/pagepics\/test\/testpics\/test.jpg"
         },
         "name2":"Company",
         "location":null,
         "logo":"https:\/\/page.com\/test\/testp\/testpics\/logo.png",
         "picture":"https:\/\/page.com\/test\/",
         "facebook":"https:\/\/www.facebook.com\/test",
         "instagram":"",
         "twitter":"",
         "telephone1":"+9611990454",
         "telephone2":"+961000000",
         "address":"Lebanon",
         "longitude":"0",
         "latitude":"0",
         "website":"www.website.com",
         "email":"",
         "desc":"asdasdas das das das dasda das das das dsadasdsadasdsad asd asd asd asd sad sa as das dsa asd das a a",
         "user":{
            "id":"21",
            "name":"X Y"
         },
         "status":"1"
      },
      {
         "id":"4",
         "category":{
            "id":"1",
            "name":"test"
         },
         "subcategory":{
            "id":"1",
            "name":"test",
            "image":"https:\/\/page.com\/test\/testp\/testpics\/test\/testphoto\/test.jpg"
         },
         "name2":"Your Company",
         "location":null,
         "logo":"",
         "picture":"https:\/\/page.com\/test\/",
         "facebook":"",
         "instagram":"",
         "twitter":"",
         "telephone1":"",
         "telephone2":"",
         "address":"",
         "longitude":"0",
         "latitude":"0",
         "website":"",
         "email":"",
         "desc":"",
         "user":{
            "id":"1",
            "name":"X Y"
         },
         "status":"1"
      }
   ]
}

我正在尝试从响应中获取所有“图像”和“名称 2”对象。 这是我的Java代码:

    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
                link, null,
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
            //            Log.d("Request", response.toString());
                         try {

                              jarray1 = response.getJSONArray("subcategory");

for(int i=0;i<jarray1.length();i++)
{
    JSONObject object = (JSONObject) jarray1.get(i);



     String url = object.getString("image");
     String name= object.getString("name2");
    Toast.makeText(getBaseContext(),url+"\n"+name,Toast.LENGTH_LONG).show();
    }



                        } catch (JSONException e) {
                            e.printStackTrace();

                        }

                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(jsonObjReq);
    }

好吧,它给了我错误的信息,有什么帮助吗?

你不能直接访问 JSON 中的内部对象,根据你的 json 格式你必须先得到 JSON Array of Companies

JSONArray companiesArray = response.getJSONArray("companies");

然后获取数组的元素

for(int i=0;i<companiesArray .length();i++){
    JSONObject object = (JSONObject) companiesArray.get(i);
    // Now get subcategory information as JSONObject 
    JSONObject subcategoryObject =object .getJSONObject("subcategory");
    // Now you can get image and name from subcategoryObject 
    String url = subcategoryObject.getString("image");
    String name= subcategoryObject.getString("name2");
}
JSONArray jAry=response.getJSONArray("companies");
for(int k=0;k<jAry.size();k++)
{
     String url = jAry.getJSONObject(k).getString("image");
     String name= jAry.getJSONObject(k).getString("name2");
}

您必须使用上面的代码才能从 json 中获取输出。 我已经给出了例如

public void SendPost() {

    HttpClient httpclient = new DefaultHttpClient();

        HttpPost httppost = new HttpPost("http://your_php_url");

        try {

            httppost.setEntity(new UrlEncodedFormEntity(postdata)); // Here postdata is BasicNameValuePair array with data to send
            HttpResponse httpResponse = httpclient.execute(httppost);
            String result = EntityUtils.toString(httpResponse.getEntity());

            GetResponce(result);

        } catch (UnsupportedEncodingException ex) {

        } catch (IOException ex) {

        } catch (JSONException ex) {

        }

}

public void GetResponce(String responce) throws JSONException {

    JSONObject myObject = new JSONObject(responce);

    JSONArray companies = myObject.getJSONArray("companies");

    String[] urls = new String[companies.length()]; 
    String[] names = new String[companies.length()]; //Here i'm initializing the arrays

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

        JSONObject object = companies.getJSONObject(i);

        JSONObject secondObject = object.getJSONObject("subcategory");

        urls[i] = secondObject.getString("image");

        names[i] = object.getString("name2");

    }

}

我想到了 :

                                try {
                                // response.getString("status");


                                    jarray = response.getJSONArray("companies");
                                  company_name=new String[jarray.length()];                     
            for(int i=0;i<jarray .length();i++){
    JSONObject object = (JSONObject) jarray.get(i);
    // Now get subcategory information as JSONObject 
   // JSONObject subcategoryObject =object .getJSONObject("subcategory");
    // Now you can get image and name from subcategoryObject 
    company_name[i]= object.getString("name2");
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM