Reputation: 2136
I want to create a JSONObject object from the URL's content, so I am getting the URL content from the google APIs, that's the result:
"results" : [
{
"address_components" : [
{
"long_name" : "29",
"short_name" : "29",
"types" : [ "street_number" ]
},
{
"long_name" : "Jean",
"short_name" : "Jean",
"types" : [ "route" ]
},
{
"long_name" : "Toulouse",
"short_name" : "Toulouse",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Haute-Garonne",
"short_name" : "31",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "Midi",
"short_name" : "Midi",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "France",
"short_name" : "FR",
"types" : [ "country", "political" ]
},
{
"long_name" : "31000",
"short_name" : "31000",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "99 Jean , 31900 Toulouse, France",
"geometry" : {
"location" : {
"lat" : 43.6069496,
"lng" : 1.4498134
},
"location_type" : "ROOFTOP",
"viewport" : {
"northeast" : {
"lat" : 43.6082985802915,
"lng" : 1.451162380291502
},
"southwest" : {
"lat" : 43.6056006197085,
"lng" : 1.448464419708498
}
}
},
"place_id" : "ChIJTSvW45i8rhIRu8OEgnpnZMY",
"types" : [ "street_address" ]
}
],
"status" : "OK"
}
I would like to create a JSONObject from this content , something like
JSONObject obj = JSONObject.fromObject(urlConnection.getInputStream());
but checking the size of this object is 0
Upvotes: 0
Views: 5630
Reputation: 19821
You need to read the content of that InputStream to a String, you can't use it directly that way.
Read the InputStream with something similar to this:
public static String slurp(InputStream is){
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
return sb.toString();
}
And then use it to get a JSONObject:
JSONObject obj = JSONObject.fromObject(slurp(urlConnection.getInputStream()));
Upvotes: 3
Reputation: 2136
Done !
JSONParser parser = new JSONParser();
Object obj = parser.parse(new InputStreamReader(inputStream));
JSONObject jsonObject = (JSONObject) obj;
Upvotes: 2