错误解析Google放置API的JSON输出

时间:2017-12-05 14:30:14

标签: android json google-places-api

我试图在使用google places API成功获取JSON后解析JSON输出,尽管代码没有显示错误,我甚至没有得到解析后的响应。   以下是在列表视图中显示它的JSON解析代码。

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class DisplayListView extends AppCompatActivity {

JSONObject jsonObject;
JSONArray jsonArray;
HotelAdapter hotelAdapter;
ListView listView;

String JSONSTR;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_display_list_view);

   this.JSONSTR=getIntent().getStringExtra("JSONmsg");
    Toast.makeText(getApplicationContext(),JSONSTR,Toast.LENGTH_SHORT).show();

    listView=(ListView)findViewById(R.id.HotelListView);

    hotelAdapter=new HotelAdapter(this,R.layout.row_layout);

    listView.setAdapter(hotelAdapter);

    try {
        jsonObject=new JSONObject(JSONSTR);
        jsonArray=jsonObject.getJSONArray("results");
        int count=0;

        String name,rating,types,vicinity;

        while (count<jsonArray.length()){
            JSONObject jo=jsonArray.getJSONObject(count);
            name=jo.getString("name");
            rating=jo.getString("rating");
            types=jo.getJSONArray("types").toString();
            vicinity=jo.getString("vicinity");

            Hotels hotels=new Hotels(name,rating,types,vicinity);
            hotelAdapter.add(hotels);
            count++;
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

}

}

,相应的JSON抓取代码为 - &gt;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.location.places.PlaceLikelihood;
import com.google.android.gms.location.places.PlaceLikelihoodBuffer;
import com.google.android.gms.location.places.Places;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class Hotel_lists extends AppCompatActivity {
    String jsonStr,JSONSTR;
    JSONObject jsonObject;
    JSONArray jsonArray;
    HotelAdapter hotelAdapter;
    ListView listView;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_hotel_lists);

}

public void getJson(View view){
    new BackTask().execute();

}

class BackTask extends AsyncTask<Void,Void,String>{

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
       jsonStr="https://maps.googleapis.com/maps/api/place/radarsearch/json?location=20.296059,85.824540&radius=500&type=hotel&key=mykey";

    }
    @Override
    protected String doInBackground(Void... voids) {
        try {
            URL url=new URL(jsonStr);
            HttpURLConnection httpURLConnection=(HttpURLConnection)url.openConnection();
            InputStream inputStream=httpURLConnection.getInputStream();
            BufferedReader bufferedReader=new BufferedReader((new InputStreamReader(inputStream)));

            StringBuilder stringBuilder=new StringBuilder();
            while((jsonStr = bufferedReader.readLine())!=null){
                stringBuilder.append(jsonStr);

            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return stringBuilder.toString().trim();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        TextView textView=(TextView)findViewById(R.id.locText);
        textView.setText(result);
        JSONSTR=result;
        Toast.makeText(getApplicationContext(),JSONSTR,Toast.LENGTH_SHORT).show();
    }
}

public void parseJson(View view){
    if(JSONSTR==null){
        Toast.makeText(getApplicationContext(),"error gettingg result",Toast.LENGTH_SHORT).show();

    }
    else{
        Toast.makeText(getApplicationContext()," gettingg result",Toast.LENGTH_SHORT).show();
       Intent intent=new Intent(this,DisplayListView.class);

       intent.putExtra("JSONmsg",JSONSTR.trim());
       startActivity(intent);

    }
}

}

这是json的回复..

{
   "html_attributions" : [],
   "next_page_token" : "CqQCGwEAAHzgWjXXoyd7FnMd3tjkgYMbo4quo3d4CZlw_HLR6yLWPbo929niHRbwAW-Ma-DaB-iqsTydif_5ggetITyGHy1jvP3r1zwD4RHdKQRYDdh8lk7wU0kiCTxp_xo9vnnrhD-Ku0LJ3ljI9Q89yvJRmFwG53opXjD1JIXd3QhWA69zUw_Dp8CvF4YJbmijDL3CKDpWRSFYRHYsOxVo8wX5ZNDBA-0JZMEeJiS77a3KsH-5miVgyHzfdbovhEctP9Yv8fvdOW1ugBWTyCpE8tdXIAIGsVpUhYmf0FE-A99LlblrttGSiVkrWCw0bXO_tyY0O_KDA-mBavlNJnDexOH3atvQz6xaMJixjwLfrzLkSA1LPc2A8EN0Q6eTB-PjOoRgRxIQqNzXJZnQ13QQebkTSF1GiBoUusO5z_TqyZlClWBh71nydS6A2gA",
   "results" : [
      {
         "geometry" : {
            "location" : {
               "lat" : 22.572646,
               "lng" : 88.36389500000001
            },
            "viewport" : {
               "northeast" : {
                  "lat" : 22.5739949802915,
                  "lng" : 88.36524398029151
               },
               "southwest" : {
                  "lat" : 22.5712970197085,
                  "lng" : 88.3625460197085
               }
            }
         },
         "icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png",
         "id" : "ab3c682ca2e068c91d806c8a443b5f7bd45145aa",
         "name" : "Sugar & Spice",
         "opening_hours" : {
            "open_now" : true,
            "weekday_text" : []
         },
         "photos" : [
            {
               "height" : 480,
               "html_attributions" : [
                  "\u003ca href=\"https://maps.google.com/maps/contrib/104833748119464497887/photos\"\u003eSugar &amp; Spice\u003c/a\u003e"
               ],
               "photo_reference" : "CmRaAAAAa7VFOzF-sjipV8a4qyD8B6v31XOwgT91SLLOmGLNVRHcWNhkhPNeOp1fTdH8yWUjhtaNEcAmnYg3G7LBI_BGeb2sVLMqNc4JH1xolP7_x8oLKkmo5XKJBtQ3-2kc7-ZIEhBUdWsuWoprBvTAfkL1_cj_GhRknB1JQe1eCTZjUNOpPdde_AV1EA",
               "width" : 640
            }
         ],
         "place_id" : "ChIJe6yzIVN2AjoRpnq6Ojv2HoM",
         "rating" : 3.2,
         "reference" : "CmRSAAAA8t4Ry-gd5HGWXZ7tN9wQNGC09gB4izm0nP1s-EGIdrbcAjCXQ7WTNzdbP2mC-x56ns8P0_19u0dIbNqk_-hCB0yYvjBL6OMx2HHAmejK8KbGDs3MGa1wiG_f6TiKAKs4EhD07l9cCpEERshxnRZGzaeqGhRDo92OY4kXdzuKRR-vMgaKjxBU7g",
         "scope" : "GOOGLE",
         "types" : [ "restaurant", "food", "point_of_interest", "establishment" ],
         "vicinity" : "78/B, Acharya Prafulla Chandra Road, Sealdah, Baithakkhana, Kolkata"
      },

所以请帮我找出错误,因为android studio没有显示任何内容虽然我可以保证我有成功的JSON提取,但最终我无法显示最终结果..

2 个答案:

答案 0 :(得分:0)

因此,在向数据集添加数据后,您没有调用notifyDatasetChanged()? 这样做,看它是否有效。

答案 1 :(得分:0)

在受保护的字符串doInBackground(Void ... voids)中

添加以下几行,而不是返回null;

data = stringBuilder.toString(); 返回数据;