Gson - 从JSON字符串获取值

时间:2015-04-05 05:12:48

标签: java android json gson

我有以下JSON字符串。我想在Gson库的帮助下获取formatted_address。我已经将对象转换为JSON。但这一次想要获取特定键的值并将其存储在字符串中。

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "Mumbai Highway",
               "short_name" : "NH 9",
               "types" : [ "route" ]
            },
            {
               "long_name" : "Kumar Swamy Nagar",
               "short_name" : "Kumar Swamy Nagar",
               "types" : [ "sublocality_level_1", "sublocality", "political" ]
            },
            {
               "long_name" : "Solapur",
               "short_name" : "Solapur",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Solapur",
               "short_name" : "Solapur",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "Maharashtra",
               "short_name" : "MH",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "India",
               "short_name" : "IN",
               "types" : [ "country", "political" ]
            },
            {
               "long_name" : "413002",
               "short_name" : "413002",
               "types" : [ "postal_code" ]
            }
         ],
         "formatted_address" : "Mumbai Highway, Kumar Swamy Nagar, Solapur, Maharashtra 413002, India",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 17.6920319,
                  "lng" : 75.9232926
               },
               "southwest" : {
                  "lat" : 17.6910298,
                  "lng" : 75.9215124
               }
            },
            "location" : {
               "lat" : 17.6915905,
               "lng" : 75.9224399
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 17.6928798302915,
                  "lng" : 75.92375148029151
               },
               "southwest" : {
                  "lat" : 17.6901818697085,
                  "lng" : 75.92105351970851
               }
            }
         },
         "place_id" : "ChIJhZADyJLaxTsRj9W-lIgGaRM",
         "types" : [ "route" ]
      }
   ],
   "status" : "OK"
}

我想解析JSON字符串ang获取“formatted_address”的值。

1 个答案:

答案 0 :(得分:2)

//result is your json data in the form of string..convert json data to string.
JSONObject returnValue = new JSONObject(result);

//getting array from json
JSONArray results= returnValue.getJSONArray("results");

for (int i = 0; i < results.length(); i++) {
  JSONObject ParentObject = results.getJSONObject(i);

  //getting particular_key...
  String format_addrs=ParentObject.getString("formatted_address");     
}