且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Java&中从JSON读取所需的数据安卓

更新时间:2022-10-14 21:38:06

将try块更改为

        while ((line = reader.readLine()) != null) {
            buffer.append(line+"\n");
        }

        Log.d("Response: ", "> " + line);
        try {
             JSONObject  jsonRootObject = new JSONObject(line);

             JSONArray jsonArray = jsonRootObject.optJSONArray("results");
             for(int i=0; i < jsonArray.length(); i++){
             JSONObject jsonObject = jsonArray.getJSONObject(i);
             data = jsonObject.getString("formatted_address")

          }

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

现在您将拥有有效的字符串到JSONObject的转换,因为以前您是在while循环中解析了不完整的字符串,而这不是有效的json.

I asked a similar question few days ago about how i could read just wanted data from JSON file in AngularJS, but i gonna do this job in java in android, so I have a problem in reading and logging JSON file like this,:

{
"results" : [
  {
     "address_components" : [
        {
           "long_name" : "277",
           "short_name" : "277",
           "types" : [ "street_number" ]
        },
        {
           "long_name" : "Bedford Avenue",
           "short_name" : "Bedford Ave",
           "types" : [ "route" ]
        },
        {
           "long_name" : "Williamsburg",
           "short_name" : "Williamsburg",
           "types" : [ "neighborhood", "political" ]
        },
        {
           "long_name" : "***lyn",
           "short_name" : "***lyn",
           "types" : [ "sublocality_level_1", "sublocality", "political" ]
        },
        {
           "long_name" : "Kings County",
           "short_name" : "Kings County",
           "types" : [ "administrative_area_level_2", "political" ]
        },
        {
           "long_name" : "New York",
           "short_name" : "NY",
           "types" : [ "administrative_area_level_1", "political" ]
        },
        {
           "long_name" : "United States",
           "short_name" : "US",
           "types" : [ "country", "political" ]
        },
        {
           "long_name" : "11211",
           "short_name" : "11211",
           "types" : [ "postal_code" ]
        }
     ],
     "formatted_address" : "277 Bedford Ave, ***lyn, NY 11211, USA",
     "geometry" : {
        "location" : {
           "lat" : 40.714232,
           "lng" : -73.9612889
        },
        "location_type" : "ROOFTOP",
        "viewport" : {
           "northeast" : {
              "lat" : 40.7155809802915,
              "lng" : -73.9599399197085
           },
           "southwest" : {
              "lat" : 40.7128830197085,
              "lng" : -73.96263788029151
           }
        }
     },
     "place_id" : "ChIJd8BlQ2BZwokRAFUEcm_qrcA",
     "types" : [ "street_address" ]
  },
  ],
  "status" : "OK"
  }

I know in Java/android we have 2 types (JSON array and JSON object and these represents with [ and { ). I just need the name of city, not all of these data. How could I log just wanted object row.

I tried this code but that doesn't work:

protected String doInBackground(String... params) {


    HttpURLConnection connection = null;
    BufferedReader reader = null;

    try {
        URL url = new URL(params[0]);
        connection = (HttpURLConnection) url.openConnection();
        connection.connect();
        InputStream stream = connection.getInputStream();
        reader = new BufferedReader(new InputStreamReader(stream));
        StringBuffer buffer = new StringBuffer();
        String line = "";
        String data = "";
        while ((line = reader.readLine()) != null) {
            buffer.append(line+"\n");
            Log.d("Response: ", "> " + line);
                try {
                    JSONObject  jsonRootObject = new JSONObject(line);


                    JSONArray jsonArray = jsonRootObject.optJSONArray("results");
                    for(int i=0; i < jsonArray.length(); i++){
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        String name = jsonObject.optString("formatted_address").toString();


                        data = name;
                    }

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

        }

        return data.toString();


    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

-------------- Edit: i used this code:

JSONObject  jsonRootObject = new JSONObject(newData);

            JSONArray jsonArray = jsonRootObject.optJSONArray("results");
            for(int i=0; i <=1 ; i++){
                JSONObject jsonObject = jsonArray.getJSONObject(i);

                data = jsonObject.getString("address_components");
            }

and now i have another json string like this:

        [
        {
           "long_name" : "277",
           "short_name" : "277",
           "types" : [ "street_number" ]
        },
        {
           "long_name" : "Bedford Avenue",
           "short_name" : "Bedford Ave",
           "types" : [ "route" ]
        },
        {
           "long_name" : "Williamsburg",
           "short_name" : "Williamsburg",
           "types" : [ "neighborhood", "political" ]
        },
        {
           "long_name" : "***lyn",
           "short_name" : "***lyn",
           "types" : [ "sublocality_level_1", "sublocality", "political" ]
        }]

how i can access to value of the "long_name" key of object(n) ?

change your try block to

        while ((line = reader.readLine()) != null) {
            buffer.append(line+"\n");
        }

        Log.d("Response: ", "> " + line);
        try {
             JSONObject  jsonRootObject = new JSONObject(line);

             JSONArray jsonArray = jsonRootObject.optJSONArray("results");
             for(int i=0; i < jsonArray.length(); i++){
             JSONObject jsonObject = jsonArray.getJSONObject(i);
             data = jsonObject.getString("formatted_address")

          }

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

Now you will have valid string to JSONObject conversion since previously you parsing incomplete string in while loop which isnt valid json.