0

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

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

我的目标是从 json 中找到位置并在我的谷歌地图视图中标记它。

这是我的异步任务类..

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 类 public class 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"
}
4

3 回答 3

1

-Mahaveer Muttha 是对的。

在这里查看 Gson 指南

Gson 用户指南和教程

于 2013-05-31T06:15:14.290 回答
0

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

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

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

于 2013-05-31T08:32:29.057 回答
0

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

//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 对象的建议值得关注。顺便说一句,Jackson 库可能是更好的 json 解析解决方案:http: //jackson.codehaus.org/

于 2013-05-31T06:26:11.103 回答