How to read json with this format - java

how can i read this JSON format,and user can pass the from and to into URL,
and want to print these from_amount and to_amount into the text view on button click.
api url
{
"from": "INR",
"to": "GBP",
"from_amount": 2,
"to_amount": 0.019798718798321
}
i tried to do the snippet below.,but it is not returning any thing and also not giving any error in thr log cat
private static final String API_URL = "http://devel.farebookings.com/api/curconversor/t1/t2/usds/json";
if (!usdValue.getText().toString().equals("")) {
AsyncHttpClient client = new AsyncHttpClient();
client.get(API_URL, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
Log.i("CHACHING", "HTTP Sucess");
try {
JSONObject jsonObj = new JSONObject(response);
JSONObject ratesObject = jsonObj
.getJSONObject("from");
JSONObject ratessObject = jsonObj
.getJSONObject("to");
JSONObject rates2Object = jsonObj
.getJSONObject("from_amount");
//Double RateTo = Double.valueOf(t2
// .toString());
Double RateFrom = Double.valueOf(t1
.toString());
// Double RateFrom = ratesObject.getDouble("from");
//Double RateTo = ratesObject.getDouble(t2.toString());
//Log.i("CHACHING", "GBP: " + gbpRate);
//Log.i("CHACHING", "EUR: " + eurRate);
Double usds = Double.valueOf(usdValue.getText()
.toString());
//Double gbps = usds * RateFrom;
// Double euros = usds * RateTo;
//Result.setText("ConvertedFrom: "
// + String.valueOf(RateFrom)+ "ConvertedTo: "
// + String.valueOf(RateTo));
Toast.makeText(getApplicationContext(),
Result.getText().toString(), Toast.LENGTH_LONG)
.show();
//ConvertedTo.setText("ConvertedTo: "
//+ String.valueOf(RateTo));
}

Don't use the getJsonObject() method to get the values inside the JSONObject, but use the corresponding getters for the types of the values. The key-value pairs themselves are no JSONObjects.
JSONObject jsonObj = new JSONObject(response);
String fromCurrency = jsonObj.getString("from");
String toCurrency= jsonObj.getJSONObject("to");
Double fromAmount = jsonObj.getDouble("from_amount");
Double toAmount= jsonObj.getDouble("to_amount");

Related

Parse JSON File with coordinates in Android

I'm new to Java and having problems with parsing json. I have a json file in res folder and need to get lat/lng from the file which will be displayed with a marker later. How can I parse the file within public void without needing to create a new Java Class or Activity?
Json
{
"type":"FeatureCollection",
"crs":{
"type":"name",
"properties":{
"name":"urn:ogc:def:crs:OGC:1.3:CRS84"
}
},
"features":[
{
"type":"Feature",
"properties":{
"MEAN_X":13.34994,
"MEAN_Y":52.54291,
"UID":"B154"
},
"geometry":{
"type":"Point",
"coordinates":[
13.34993674,
52.54291394
]
}
},
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
JSONObject jsonObj = new JSONObject(R.raw.level1_points);
final String TAG_FEATURES = jsonObj.getString("features");
final String TAG_PROPERTIES = jsonObj.getString("properties");
final double TAG_MEANX = jsonObj.getDouble("MEAN_X");
final double TAG_MEANY = jsonObj.getDouble("MEAN_X");
final String TAG_UID = jsonObj.getString("UID");
try {
JSONArray features = jsonObj.getJSONArray(TAG_FEATURES);
for (int i = 0; i < features.length(); i++) {
// Create a marker for each room in the JSON data.
JSONObject c = features.getJSONObject(i);
JSONObject properties = c.getJSONObject(TAG_PROPERTIES);
Double MEAN_X = properties.getDouble(TAG_MEANX);
Double MEAN_Y = properties.getDouble(TAG_MEANY);
String UID = properties.getString(TAG_UID);
if (spinner.getSelectedItem().toString().equals(UID)) {
LatLng room = new LatLng(MEAN_X; MEAN_Y);
mMap.addMarker(new MarkerOptions().position(raum).title("Room"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(room));
mMap.animateCamera(CameraUpdateFactory.zoomTo(16));
<code>
you can do the following changes
first you'll have to get the json file from the res folder
and then parse the json data
// get the json file
InputStream inputStream = getResources().openRawResource(R.raw.level1_points);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int ctr;
try {
ctr = inputStream.read();
while (ctr != -1) {
byteArrayOutputStream.write(ctr);
ctr = inputStream.read();
}
inputStream.close();
String jsonString = byteArrayOutputStream.toString();
Log.v("Text Data", jsonString);
JSONObject jsonObj = new JSONObject(jsonString);
JSONArray features = jsonObj.getJSONArray("features");
for (int i = 0; i < features.length(); i++) {
// Create a marker for each room in the JSON data.
JSONObject c = features.getJSONObject(i);
JSONObject properties = c.getJSONObject("properties");
Double MEAN_X = properties.getDouble("MEAN_X");
Double MEAN_Y = properties.getDouble("MEAN_Y");
String UID = properties.getString("UID");
Log.e(TAG, "onCreate: " + MEAN_X + MEAN_Y + UID);
}
} catch (Exception e) {
Log.e(TAG, "onCreate: " + e.getMessage());
}

Parsing JSON string in Java android

I want to extract elements (state,county ) from this JSON string :
I am trying to parse a JSON string in java to have the individual value printed separately. But while making the program run I get nothing.
"place": [
{
"address": {
"country_code": "fr",
"country": "France",
"state": "Normandie",
"county": "Calvados"
},
"icon": "http://nominatim.openstreetmap.org/images/mapicons/poi_boundary_administrative.p.20.png",
"importance": 0.74963706049207,
"type": "administrative",
"class": "boundary",
"display_name": "Calvados, Normandie, France",
"lon": "-0.24139500722798",
"lat": "49.09076485",
"boundingbox": [
"48.7516623",
"49.4298653",
"-1.1597713",
"0.4466332"
],
"osm_id": "7453",
"osm_type": "relation",
"licence": "Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright",
"place_id": "158910871"
}
]
any help would be appreciated. thanks.
these is my android code :
JSONObject objectPremium = new JSONObject(String.valueOf(result));
String premium = objectPremium.getString("premium");
JSONArray jArray1 = objectPremium.getJSONArray("premium");
for(int i = 0; i < jArray1.length(); i++)
{
JSONObject object3 = jArray1.getJSONObject(i);
adresse = object3.getJSONObject("place").getJSONObject("address").getString("state");
Log.e("mylog",adresse);
}
In your JSON string, "place" is a JSONArray and its containing another JSONObject. Get "place" value as below:
// Place
JSONArray place = jsonObj.getJSONArray("place");
Get "address" value as below:
// Address
JSONObject address = place.getJSONObject(0).getJSONObject("address");
Get "countryCode", "country", "state" and "county" value as below:
String countryCode = address.getString("country_code");
String country = address.getString("country");
String state = address.getString("state");
String county = address.getString("county");
Here is the fully working code. Try this:
public void parseJson() {
// Your JOSON string
String jsonStr = "{\"place\": [\n" +
" {\n" +
" \"address\": {\n" +
" \"country_code\": \"fr\",\n" +
" \"country\": \"France\",\n" +
" \"state\": \"Normandie\",\n" +
" \"county\": \"Calvados\"\n" +
" },\n" +
" \"icon\": \"http://nominatim.openstreetmap.org/images/mapicons/poi_boundary_administrative.p.20.png\",\n" +
" \"importance\": 0.74963706049207,\n" +
" \"type\": \"administrative\",\n" +
" \"class\": \"boundary\",\n" +
" \"display_name\": \"Calvados, Normandie, France\",\n" +
" \"lon\": \"-0.24139500722798\",\n" +
" \"lat\": \"49.09076485\",\n" +
" \"boundingbox\": [\n" +
" \"48.7516623\",\n" +
" \"49.4298653\",\n" +
" \"-1.1597713\",\n" +
" \"0.4466332\"\n" +
" ],\n" +
" \"osm_id\": \"7453\",\n" +
" \"osm_type\": \"relation\",\n" +
" \"licence\": \"Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright\",\n" +
" \"place_id\": \"158910871\"\n" +
" }\n" +
" ]}";
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Place
JSONArray place = jsonObj.getJSONArray("place");
// Address
JSONObject address = place.getJSONObject(0).getJSONObject("address");
String countryCode = address.getString("country_code");
String country = address.getString("country");
String state = address.getString("state");
String county = address.getString("county");
Log.d("SUCCESS", "State: " + state + " Country: " + country + " County: " + county);
} catch (final JSONException e) {
Log.e("FAILED", "Json parsing error: " + e.getMessage());
}
}
}
Hope this will help~
The first thing you need is to make sure you are receiving this string or not. I am assuming you are trying to fetch it from some URL.
To fetch the JSON you can use the following code snippet.
private void getJSON(final String urlWebService) {
class GetJSON extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(urlWebService);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json + "\n");
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
GetJSON getJSON = new GetJSON();
getJSON.execute();
}
You need to pass your URL to this function. And if calling this method is displaying the JSON data that you are expecting then the first part is done. You have the JSON string in onPostExecute() method.
Now you can easily parse this string if it contains a valid JSON data. But the JSON that you shown in your question does not seems a valid JSON. I guess it is only part of a big JSON file. So if you need the exact code to parse your JSON post the full JSON.
Pat parsing is very easy. If the json you have is an object create an instance of JSONObject if it is an array create an instance of JSONObject.
Then you can easily get the keys if it is an object. Or you can traverse through items if it is an array.
For more details you can check this JSON Parsing in Android post.
Change for this:
JSONObject objectPremium = new JSONObject(String.valueOf(result));
String premium = objectPremium.getString("premium");
JSONArray jArray1 = objectPremium.getJSONArray("premium");
for(int i = 0; i < jArray1.length(); i++)
{
JSONObject object3 = jArray1.getJSONObject(i);
JSONArray placeArray = object3.getJSONArray("place")
JSONObject addressObject = placeArray.getJSONObject("address");
adress = addressObject.getString("state");
Log.e("mylog",adresse);
}
If your initial part of the JSON Parsing code is correct, then this should work!
JSONArray jArray = new JSONArray(result);
JSONObject objectPremium = jArray.get(0);
JSONObject json = jsonObject.getJSONObject("address");
String state = json.getString("state");
String country = json.getString("country");
Check this code,
this is how you parse and store in a list
String jsonStr = //your json string
HashMap<String, String> addressList= new HashMap<>();
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray address = jsonObj.getJSONArray("address"); // for the address
// looping through All that
for (int i = 0; i < address.length(); i++) {
JSONObject c = address.getJSONObject(i);
String country_code= c.getString("country_code");
String country= c.getString("country");
String state= c.getString("state");
String county = c.getString("county");
// adding each child node to HashMap key => value
address.put("country_code", country_code);
address.put("country", country);
address.put("state", state);
address.put("county", county);
// adding address to address list
addressList.add(address);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}

How to extract this JSON response

I want to extract
the val from the first array
SVCNO and PATH from the second array
PROBLEM: However, I cannot seem to extract anything due to this error:
This interface was deprecated in API level 22. Please use openConnection() instead. Please visit this webpage for further details.
These are my codes:
//where URL4 = http://www.onemap.sg/BusServiceAPI/Service1.svc/showRoute?token=489ce5de815c81c7fda85af3980e9b6258124ca68837e425a2b7373c2d869bbf9ea4ad5a4901fbce20da45b4e095643b&svc=39%7C1%3B85%7C1%3B169%7C1%3B811%7C1%3B851%7C1%3B852%7C1%3B854%7C1%3B854E%7C1%3B858%7C1%3B965%7C1%3B969%7C1
List<NameValuePair> URLparams4 = new LinkedList<NameValuePair();
URLparams4.add(new BasicNameValuePair(PARAM_TOKEN, TOKEN));
URLparams4.add(new BasicNameValuePair(PARAM_SVC, joinBusDirAndSvc));
String paramString4 = URLEncodedUtils.format(URLparams4,"utf-8");
String url4 = BusShowRoute_URL + paramString4;
ResponseHandler<String>handler4 = new BasicResponseHandler();
HttpGet get4 = new HttpGet(url4);
HttpParams httpParameters4 = new BasicHttpParams();
DefaultHttpClient client4 = new DefaultHttpClient (httpParameters4);
try
{
String response4 = client4.execute(get4,handler4);
System.out.println("busesponse4= " + response4); //response array
//convert result page into JSON Object
JSONObject jsonResponse4= new JSONObject(response4);
//get JSON Array
jsArray_busRoute = jsonResponse4.getJSONArray(ATTR_BUSROUTE);
System.out.print("jsArray_busRoute== " + jsArray_busRoute);
for (int i = 0; i < jsArray_busRoute.length(); i++)
{
JSONObject obj_busRoute = jsArray_busRoute.getJSONObject(i);
if (!obj_busRoute.has(ATTR_PAGECOUNT))
{
String val = obj_busRoute.getString(ATTR_VAL + i);
System.out.print("val== " + val);
}
}
}
Below is the JSON response:
{
"BusRoute":
{
"PageCount":[
{
"Val0":"TAMPINES INT,
YISHUN TEMP INT"
},
{
"Val1":"PUNGGOL TEMP INT,
YISHUN TEMP INT"
}
],
"1":[
{
"SVCNO":"39",
"DRC":"1",
"SQNO":"1",
"DST":"0",
"SBS":"75009",
"EBS":"76059",
"PATH":"40287.2481620079,37450.8849868048;
40298.2076238208,37458.4535869379;
40309.8456332916,37470.8674859032;
40320.7077835361,37487.9365402292;
40326.1859934768,37512.3384070937;
40255.2463979153,37512.7719051559;
}
]
}
}
Thank you for helping!

How to parse a multi-array JSON (Java)

I'm currently working on a project that requires the latitude and longitude of a given address (input). Google maps API returns in json format, and I've done research and found that json-simple is the best option for my project. I have this code as well as the String output from google maps API, and would highly appreciate some help in parsing properly.
Also note: the call: MapTile.receiveJson just returns the string from google's API (linked below)
try {
String jsonAdr = MapTile.receiveJson("http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA");
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject)parser.parse(jsonAdr);
System.out.println("lat=" + json.get("address_components"));
} catch (Exception e1) {e1.printStackTrace();System.out.println("Error contacting google or invalid input");}
This is the exact string output from google's API:
http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA
I realize I could do String parsing, however it would be inefficient as I will be using more of google's API. I have also viewed other stack overflow, as well as their JSON website but found no examples with multiple JSON arrays such as those returned by google.
Any help is greatly appreciated.
Here's the solution:
I basically made a stand alone and I parsed your JSON like this:
First : This is the method I used to parse the JSON:
public String loadJSON(String someURL) {
String json = null;
HttpClient mHttpClient = new DefaultHttpClient();
HttpGet mHttpGet = new HttpGet(someURL);
try {
HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet);
StatusLine statusline = mHttpResponse.getStatusLine();
int statusCode = statusline.getStatusCode();
if (statusCode != 200) {
return null;
}
InputStream jsonStream = mHttpResponse.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
jsonStream));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
json = builder.toString();
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
mHttpClient.getConnectionManager().shutdown();
return json;
}
Second : Used Async Task to download the data:
public class BackTask extends AsyncTask<Void, Void, Void> {
String url;
public BackTask(String URL) {
super();
this.url = URL;
}
#Override
protected Void doInBackground(Void... params) {
getData(url);
return null;
}
}
Third: Method to get the data and parse it. I have made some comments for this part since it's a bit long than usual.
public void getData(String URL) {
try {
JSONObject mainJsonObject = new JSONObject(loadJSON(URL));
// Log.d("JSON Data : ", mainJsonObject.toString());
String Status = mainJsonObject.getString("status");
Log.d("JSON Status : ", Status + "\n" + "---------------------");
JSONArray mainArray = mainJsonObject.getJSONArray("results");
// Log.d("JSON Array : ", mainArray.toString());
for (int i = 0; i < mainArray.length(); i++) {
JSONObject insideJsonObject = mainArray.getJSONObject(i);
if (insideJsonObject != null) {
String address_components = insideJsonObject
.getString("address_components");
// Log.d("Inside JSON Array : ", address_components);
JSONArray addressJSON = insideJsonObject
.getJSONArray("address_components");
// Log.d("Inside JSON ADDress : ", addressJSON.toString());
String formatted_address = insideJsonObject
.getString("formatted_address");
Log.d("Inside JSON formatted_address : ", formatted_address
+ "\n" + "-----------");
for (int ji = 0; ji < mainArray.length(); ji++) {
JSONObject geoMetryJO = mainArray.getJSONObject(ji);
if (geoMetryJO != null) {
JSONObject geometry = geoMetryJO
.getJSONObject("geometry");
// Log.d("Inside JSON geometry : ",
// geometry.toString()+"\n"+"----------");
String location_type = geometry
.getString("location_type");
Log.d("Inside JSON location_type : ", location_type
+ "\n" + "------------");
JSONObject locationJSONObject = geometry
.getJSONObject("location");
String Latitude = locationJSONObject
.getString("lat");
Log.d("Inside JSON Latitude : ", Latitude + "\n"
+ "--------------");
String Longitude = locationJSONObject
.getString("lng");
Log.d("Inside JSON Longitude : ", Longitude + "\n"
+ "------------");
JSONObject viewportJSONObject = geometry
.getJSONObject("viewport");
// Log.d("Inside JSON viewportJSONObject : ",
// viewportJSONObject.toString()+"\n"+"------------");
JSONObject northeastJSONObject = viewportJSONObject
.getJSONObject("northeast");
String Lat = northeastJSONObject.getString("lat");
Log.d("Inside JSON Lat : ", Lat + "\n"
+ "------------");
String Lon = northeastJSONObject.getString("lng");
Log.d("Inside JSON Lon : ", Lon + "\n"
+ "------------");
JSONObject southwestJSONObject = viewportJSONObject
.getJSONObject("southwest");
String south_Lat = southwestJSONObject
.getString("lat");
Log.d("Inside JSON south_Lat : ", south_Lat + "\n"
+ "------------");
String south_Lon = southwestJSONObject
.getString("lng");
Log.d("Inside JSON south_Lon : ", south_Lon + "\n"
+ "------------");
}
}
for (int k = 0; k < addressJSON.length(); k++) {
JSONObject addressJSONObject = addressJSON
.getJSONObject(k);
if (addressJSONObject != null) {
String long_name = addressJSONObject
.getString("long_name");
Log.d("Inside JSON LongName : ", long_name);
String short_name = addressJSONObject
.getString("short_name");
Log.d("Inside JSON ShortName : ", short_name);
JSONArray addressJSONArray = addressJSONObject
.getJSONArray("types");
Log.d("Inside JSON JSONADD : ",
addressJSONArray.toString() + "\n"
+ "-------------");
}
}
JSONArray insideJsonArray = insideJsonObject
.getJSONArray("types");
Log.d("Inside JSON Types : ", insideJsonArray.toString());
String street = insideJsonObject.getString("types");
Log.d("Inside JSON Street : ", street);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
After getting all the data, you can use it in anyway you want cause it's mostly in the string format. You can just copy and paste this method and it should run fine.
Fourth : On the onCreate() method, just executed the task like this:
public static final String URL = "http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new BackTask(URL).execute();
}
This was the complete solution for this question. Let me know if have any questions for this. Hope this helps..Good Luck.. :)
I did this for formatted_address. I type casted explicitly here. But getJSONArray () and getJSONObject() methods will perform the typecasting too.
// parse the Result String to JSON
JSONObject myJSONResult = new JSONObject(results);
for (int i = 0; i <((JSONArray) myJSONResult.get("results")).length(); i++)
System.out.println(((JSONObject) ((JSONArray) myJSONResult.get("results")).get(i)).get("formatted_address")); // This is your final options.

How can I iterate JSONObject to get individual items

This is my below code from which I need to parse the JSONObject to get individual items. This is the first time I am working with JSON. So not sure how to parse JSONObject to get the individual items from JSONObject.
try {
String url = service + version + method + ipAddress + format;
StringBuilder builder = new StringBuilder();
httpclient = new DefaultHttpClient();
httpget = new HttpGet(url);
httpget.getRequestLine();
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = entity.getContent();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
for (String line = null; (line = bufferedReader.readLine()) != null;) {
builder.append(line).append("\n");
}
JSONObject jsonObject = new JSONObject(builder.toString());
// Now iterate jsonObject to get Latitude,Longitude,City,Country etc etc.
}
} catch (Exception e) {
getLogger().log(LogLevel.ERROR, e.getMessage());
} finally {
bufferedReader.close();
httpclient.getConnectionManager().shutdown();
}
My JSON looks like this:
{
"ipinfo": {
"ip_address": "131.208.128.15",
"ip_type": "Mapped",
"Location": {
"continent": "north america",
"latitude": 30.1,
"longitude": -81.714,
"CountryData": {
"country": "united states",
"country_code": "us"
},
"region": "southeast",
"StateData": {
"state": "florida",
"state_code": "fl"
},
"CityData": {
"city": "fleming island",
"postal_code": "32003",
"time_zone": -5
}
}
}
}
I need to get latitude, longitude, city, state, country, postal_code from the above object. Can anyone provide any suggestion how to do it efficiently?
You can try this it will recursively find all key values in a json object and constructs as a map . You can simply get which key you want from the Map .
public static Map<String,String> parse(JSONObject json , Map<String,String> out) throws JSONException{
Iterator<String> keys = json.keys();
while(keys.hasNext()){
String key = keys.next();
String val = null;
try{
JSONObject value = json.getJSONObject(key);
parse(value,out);
}catch(Exception e){
val = json.getString(key);
}
if(val != null){
out.put(key,val);
}
}
return out;
}
public static void main(String[] args) throws JSONException {
String json = "{'ipinfo': {'ip_address': '131.208.128.15','ip_type': 'Mapped','Location': {'continent': 'north america','latitude': 30.1,'longitude': -81.714,'CountryData': {'country': 'united states','country_code': 'us'},'region': 'southeast','StateData': {'state': 'florida','state_code': 'fl'},'CityData': {'city': 'fleming island','postal_code': '32003','time_zone': -5}}}}";
JSONObject object = new JSONObject(json);
JSONObject info = object.getJSONObject("ipinfo");
Map<String,String> out = new HashMap<String, String>();
parse(info,out);
String latitude = out.get("latitude");
String longitude = out.get("longitude");
String city = out.get("city");
String state = out.get("state");
String country = out.get("country");
String postal = out.get("postal_code");
System.out.println("Latitude : " + latitude + " LongiTude : " + longitude + " City : "+city + " State : "+ state + " Country : "+country+" postal "+postal);
System.out.println("ALL VALUE " + out);
}
Output:
Latitude : 30.1 LongiTude : -81.714 City : fleming island State : florida Country : united states postal 32003
ALL VALUE {region=southeast, ip_type=Mapped, state_code=fl, state=florida, country_code=us, city=fleming island, country=united states, time_zone=-5, ip_address=131.208.128.15, postal_code=32003, continent=north america, longitude=-81.714, latitude=30.1}
How about this?
JSONObject jsonObject = new JSONObject (YOUR_JSON_STRING);
JSONObject ipinfo = jsonObject.getJSONObject ("ipinfo");
String ip_address = ipinfo.getString ("ip_address");
JSONObject location = ipinfo.getJSONObject ("Location");
String latitude = location.getString ("latitude");
System.out.println (latitude);
This sample code using "org.json.JSONObject"

Categories

Resources