Json解析以获取android中最近的加油站

时间:2013-05-31 06:03:19

标签: android json parsing

我正在解析json,这是一个json object开始。它有一个数组html_attributions[]和另一个数组results[]

现在,当我从json创建URL字符串时,我可以看到我的json字符串即将到来。但是在从json字符串创建json对象时,我有illegalArugumentExceptionillegal character in scheme at index 0

我的目标是从json中找到位置并在我的google mapview中标记。

这是我的asynctask类..

class LocationJSON extends AsyncTask<String, Integer, Long> {

        @Override
        protected Long doInBackground(String... arg0) {
            // TODO Auto-generated method stub

            JSONParser jParser = new JSONParser();String url = jParser.getJSONStringFromUrl("https://maps.googleapis.com/maps/api/place/search/json?location=37.78583400,-122.40641700&radius=1500&types=gas_station&sensor=true&key=AIzaSyBIwW4m6xINOhM_j7hckMAbD3oks_fkLFc");

            //main json abject
            jsonObject = jParser.getJSONObject(url);


            //get to the results array:
            try {
                JSONArray htmlArray = jsonObject.getJSONArray("html_attributions");
                JSONArray resultsArray = jsonObject.getJSONArray("results");

                //get to the geometry objects
                for (int i = 0; i < resultsArray.length(); i++) {
                    JSONObject geometry = resultsArray.getJSONObject(i);


                    //get to the location object
                    JSONObject location = geometry.getJSONObject("location");

                    //get to the lat string
                    double lati = Double.parseDouble(location.getString("Lat"));
                    double longi = Double.parseDouble(location.getString("lng"));

                    //create a latlong object
                    place = new LatLng(lati,longi);

                      /*//set the map
                    Marker melbourne = map.addMarker(new MarkerOptions()
                    .position(place)

                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));


                    //set the camera
                    cameraUpdate = CameraUpdateFactory.newLatLngZoom(place, 10);
                        map.animateCamera(cameraUpdate);*/


                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Long result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);


            //set the map
        Marker melbourne = map.addMarker(new MarkerOptions()
        .position(place)

        .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));


        //set the camera
         CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(place, 10);

         map.animateCamera(cameraUpdate);

        }

    }

//这是我的jsonparser类公共类JSONParser {

static InputStream is = null;

    static JSONObject jObj = null;

    static String json = "";

    static JSONArray jArray = null;



    // constructor

    public JSONParser() {

    }

    public String getJSONStringFromUrl(String url) {


        // Making HTTP request

        try {

            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()

                    .permitAll().build();


            StrictMode.setThreadPolicy(policy);

            // defaultHttpClient

            DefaultHttpClient httpClient = new DefaultHttpClient();

            HttpPost httpPost = new HttpPost(url);


            HttpResponse httpResponse = httpClient.execute(httpPost);

            HttpEntity httpEntity = httpResponse.getEntity();

            is = httpEntity.getContent();


        } catch (UnsupportedEncodingException e) {

            e.printStackTrace();

        } catch (ClientProtocolException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        }    

        try {

            BufferedReader reader = new BufferedReader(new InputStreamReader(

                    is, "iso-8859-1"), 8);

            StringBuilder sb = new StringBuilder();

            String line = null;

            while ((line = reader.readLine()) != null) {

                sb.append(line + "\n");

            }

            is.close();

            json = sb.toString();

        } catch (Exception e) {

            Log.e("Buffer Error", "Error converting result " + e.toString());

        }  


        // return JSON String

        return json;


    }    

    public JSONObject getJSONObject(String url) {

        // try parse the string to a JSON object


        getJSONStringFromUrl(url);

        try {

            jObj = new JSONObject(json);

        } catch (JSONException e) {

            Log.e("JSON Parser Object",

                    "Error parsing jsonObject " + e.toString());

        }   


        // return JSON String

        return jObj;

    }   

    public JSONArray getJSONArray(String url) {

        // try parse the string to a JSON array


        getJSONStringFromUrl(url);

        try {

            jArray = new JSONArray(json);

        } catch (JSONException e) {

            Log.e("JSON Parser Array",

                    "Error parsing jsonArray " + e.toString());

        }    

        // return JSON String

        return jArray;   

    }
} 

这里是json数据

{
  "html_attributions": [

  ],
  "results": [
    {
      "geometry": {
        "location": {
          "lat": 37.7774450,
          "lng": -122.4048230
        }
      },
      "icon": "http://maps.gstatic.com/mapfiles/place_api/icons/gas_station-71.png",
      "id": "8e31a915604dd3597225152bfd3ec6f9bfa39395",
      "name": "Chevron",
      "photos": [
        {
          "height": 640,
          "html_attributions": [
            "From a Google User"
          ],
          "photo_reference": "CnRiAAAADAcSOQpR_AW86egDLCWLpuEf00zuXUVFbcxh5-zCY5OzIUtJx764rn2mLnWTMA0xsz3AG7e0ZbU3n_GTJcOI0O15N1Va34GhUMiXirAw6h0DUETlElRwzvNjv1sQoFdimUYCOg-Us4ow9hoeq4cx-RIQSqRYof89YFdoVKRokkHN6RoUT4nJ4eofBuD1pJgwVeIKiaOlVo4",
          "width": 480
        }
      ],
      "rating": 3.20,
      "reference": "CnRkAAAAQ8TbCf9PqmO-_2-vgbFdrKE9j5PIknybR43IdTMziGYAuj5yOW3PcCCfLMgaeEM0ulLWU2WI3-YX14d1bza8tDYAEQlsP4JMTRT1RAeCm_CzhhhcZaB6UZ2Q2_f33iNHxMvoPumNwef6OXXmPQkusxIQ80SUv_R8odDO1dds5ovKZBoURT26TM5W2qKebWGQxfPE0SRgLwQ",
      "types": [
        "car_repair",
        "gas_station",
        "establishment"
      ],
      "vicinity": "1000 Harrison Street, San Francisco"
    },

      ],

  "status": "OK"
}

3 个答案:

答案 0 :(得分:1)

-Mahaveer Muttha是对的。

在这里查看Gson指南

Gson User Guide with tutorial

答案 1 :(得分:0)

我如何解析谷歌地方响应以获取位置名称:

//data is a String with your JSON
JSONObject jsonObject = new JSONObject(data);
JSONArray googlePlaces = jsonObject.getJSONArray("results");
String[] googlePlacesNames = getStringFromJsonArray(googlePlaces, "name");

private String[] getStringFromJsonArray(JSONArray source, String fieldName){
        String result[] = new String[source.length()];
        JSONObject json;
        try {
            for (int i=0; i<source.length();i++) {
                json = source.getJSONObject(i);
                result[i]=json.getString("name");
                Log.d("Places", "Next museum: " + result[i]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  result;
    }

使用GSON解析JSON对象的建议值得关注。顺便说一下,杰克逊库可以成为json解析的更好解决方案:http://jackson.codehaus.org/

答案 2 :(得分:0)

这种将JSON String传递给Object的方式更容易出错。我的建议是使用Spring RestTemplate你不必手动操作JSON对象。在序列化和淡化JSON字符串时,RestTemplate将为您完成所有工作。您只需要一个实体类,您将拥有与加油站相关的所有字段。您甚至可以从RestTemplate申请加油站列表。这是一个处理Java对象的问题,而不是手动操作JSON字符串的负担。

RestTemplate restTemplate = new RestTemplate();
List<GasStation> stations = (List) restTemplate.getForObject(yourURL, List.class);

以上代码将为您提供代码中的加油站列表。