如何在Java和Java中从JSON读取想要的数据Android的

时间:2016-06-03 14:38:53

标签: java android json

前几天我问了一个类似的问题,关于如何从AngularJS中的JSON文件中读取想要的数据,但我会在android中的java中做这个工作,所以我在读取和记录这样的JSON文件时遇到了问题, :

{
"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" : "Brooklyn",
           "short_name" : "Brooklyn",
           "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, Brooklyn, 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"
  }

我知道在Java / android中我们有两种类型(JSON数组和JSON对象,它们用[和{代表)。我只需要城市名称,而不是所有这些数据。我怎么能只记录想要的对象行。

我尝试过这段代码,但这不起作用:

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;
}

-------------- 修改: 我用了这段代码:

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");
            }

现在我有另一个像这样的json字符串:

        [
        {
           "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" : "Brooklyn",
           "short_name" : "Brooklyn",
           "types" : [ "sublocality_level_1", "sublocality", "political" ]
        }]

我如何访问&#34; long_name&#34;的值对象(n)的关键?

5 个答案:

答案 0 :(得分:2)

将您的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。

答案 1 :(得分:0)

您需要等到所有输入都被读取。换句话说,所有JSON Handling代码都应该不在while循环中。

答案 2 :(得分:0)

您可以使用JSON库来解析此对象:

public class JsonValue {
    public static void main(String[] args) throws JSONException {
        String jsonString = "{ \"field1\" : \"value1\", \"city\" : \"New York\", \"address\" : \"address1\" }";
        JSONObject jsonObject = new JSONObject(jsonString);
        String city = jsonObject.getString("city");
        System.out.println(city);
     }
}

答案 3 :(得分:0)

或者您可以使用GSON:

Gson gson = new Gson();
Type type = new TypeToken<List<AddressComponents>>() {}.getType();
List<AddressComponents> fromJson = gson.fromJson(json, type);

http://www.vogella.com/tutorials/JavaLibrary-Gson/article.html

答案 4 :(得分:0)

首先创建这两个模型:

public class ResultModel{
    public string formatted_address;
}

public class ResponseModel{
    public List<ResultModel> results;
}

然后通过以下地址获取您的地址:

Gson gson = new Gson();
ResponseModel response = gson.fromJson(json, ResponseModel.class);

response.results // this is your list of "formatted addresses"

可以循环迭代或在任何地方使用。所有其他json都将被忽略。

确保包含在您的gradle中:

compile 'com.google.code.gson:gson:2.4'