简体   繁体   English

如何在Java和Android中从JSON读取所需数据

[英]How to just read wanted data from JSON in Java & Android

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,: 几天前,我问了一个类似的问题,关于如何从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"
  }

I know in Java/android we have 2 types (JSON array and JSON object and these represents with [ and { ). 我知道在Java / android中,我们有2种类型(JSON数组和JSON对象,它们用[和{)表示。 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: 现在我有另一个像这样的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" ]
        }]

how i can access to value of the "long_name" key of object(n) ? 我如何才能访问object(n)的“ long_name”键的值?

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. 现在您将拥有有效的字符串到JSONObject转换,因为以前您在while循环中解析了不完整的字符串,而这不是有效的json。

You need to wait until all the input has been read. 您需要等待,直到所有输入都已被读取。 In other words, all of the JSON Handling code should be out of the while loop. 换句话说,所有JSON处理代码都应该不在while循环中。

You can use the JSON library to parse this object: 您可以使用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);
     }
}

Or you can use GSON: 或者您可以使用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 http://www.vogella.com/tutorials/JavaLibrary-Gson/article.html

First create this two models: 首先创建这两个模型:

public class ResultModel{
    public string formatted_address;
}

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

then get your addresses with: 然后通过以下方式获取您的地址:

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

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

Can be iterated with for cycle or used anywhere. 可以循环使用或在任何地方使用。 All other json will be ignored. 所有其他json将被忽略。

make sure to include in your gradle: 确保包括在您的gradle中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM