How to read JSON object in kotlin with Volle Android Studio? - json

I'm using volley to read a Get Request from the Google Places API and I want to get some information from this JSON OUTPUT:
"results": [
{
"business_status": "OPERATIONAL",
"geometry": {
"location": {
"lat": 25.7239497,
"lng": -100.1915475
},
"viewport": {
"northeast": {
"lat": 25.7252242302915,
"lng": -100.1902086197085
},
"southwest": {
"lat": 25.7225262697085,
"lng": -100.1929065802915
}
}
},
"icon": "https://maps.gstatic.com/mapfiles/place_api/icons/v1/png_71/restaurant-71.png",
"icon_background_color": "#FF9E67",
"icon_mask_base_uri": "https://maps.gstatic.com/mapfiles/place_api/icons/v2/restaurant_pinlet",
"name": "El Texanito",
"opening_hours": {},
"photos": [],
"place_id": "ChIJJdu3AjbqYoYRPJyEgQwBT-0",
"plus_code": {},
"price_level": 2,
"rating": 4,
"reference": "ChIJJdu3AjbqYoYRPJyEgQwBT-0",
"scope": "GOOGLE",
"types": [],
"user_ratings_total": 563,
"vicinity": "Boulevard Acapulco #141, Josefa Zozaya, Guadalupe"
},
My kotlin Code:
fun methodToGetInfo(){
tbUsuarios?.removeAllViews()
var queue = Volley.newRequestQueue(this)
var url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?fields=price_level&location=25.7299374%2C-100.2096866&radius=2500&type=restaurant&key=AIzaSyDV6aFItX960hrbAaI229-8iDa3xTZ-RXU"
var myJsonObjectRequest = JsonObjectRequest(Request.Method.GET,url,null,
Response.Listener {
response -> try{
var myJsonArray = response.getJSONArray("results")
for(i in 0 until myJsonArray.length()){
var myJSONObject = myJsonArray.getJSONObject(i)
val registro = LayoutInflater.from(this).inflate(R.layout.table_row_np,null,false)
val colName = registro.findViewById<View>(R.id.columnaNombre) as TextView
val colPrice = registro.findViewById<View>(R.id.columnaEmail) as TextView
val colLatitude = registro.findViewById<View>(R.id.colEditar)
val colBorrar = registro.findViewById<View>(R.id.colBorrar)
colName.text= myJSONObject.getString("name")
Log.d(TAG, "Nombre: ${ myJSONObject.getString("name")}" )
Log.d(TAG, "Rating: ${ myJSONObject.getString("price_level")}" )
colPrice.text=myJSONObject.getString("price_level")
Log.d(TAG, "Latitude: ${myJSONObject.getString("location")}")
tbUsuarios?.addView(registro)
}
I can easily get information like the name, price rating, place_id, etc but when I need to get data inside some properties like for example lat, I am getting an error.
I know that simply searching for "lat" is wrong because I need to travel "geometry" -> "location" -> "lat"
I want to know how to travel through these properties and get that information

Assuming the type is org.json.JSONObject, you can use something like
myJSONObject.getJSONObject("geometry").getJSONObject("location").getString("lat")
If the fields aren't guaranteed to be present, use safe calls:
myJSONObject.getJSONObject("geometry")?.getJSONObject("location")?.getString("lat")
Of course if you want to access more than one property from the same path it can make sense to use a local variable too, e.g.
val location = myJSONObject.getJSONObject("geometry").getJSONObject("location")
val latitude = location.getString("lat")
val longitude = location.getString("lng")

Related

How do I load a JSON file into the DOM in Saxon running in Java?

In my Java code I am trying to create a Saxon document (DOM) that is the contents of a JSON file. This should be possible but the code I have fails.
The full code for this is at SaxonQuestions.zip, TestLoadJson.java and is also listed below. In this code the evaluate() fails.
TestLoadJson.java
import net.sf.saxon.Configuration;
import net.sf.saxon.s9api.*;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import javax.xml.transform.sax.SAXSource;
import java.io.*;
import java.nio.charset.Charset;
public class TestLoadJson {
public static void main(String[] args) throws Exception {
// get the file
File jsonFile = new File("files", "SouthWind.json");
Charset inputCharset = Charset.forName("UTF-8");
FileInputStream fis = new FileInputStream(jsonFile);
InputStreamReader isr = new InputStreamReader(fis, inputCharset);
BufferedReader br = new BufferedReader(isr);
String str;
StringBuilder buf = new StringBuilder();
while ((str = br.readLine()) != null)
buf.append(str).append('\n');
br.close();
isr.close();
fis.close();
// set up the compiler
Configuration config = XmlDatasource.createEnterpriseConfiguration();
Processor processor = new Processor(config);
XPathCompiler xPathCompiler = processor.newXPathCompiler();
// need an XML document
DocumentBuilder doc_builder = processor.newDocumentBuilder();
XMLReader reader = XmlDatasource.createXMLReader();
InputSource xmlSource = new InputSource(new ByteArrayInputStream("<root/>".getBytes()));
SAXSource saxSource = new SAXSource(reader, xmlSource);
XdmNode xmlRootNode = doc_builder.build(saxSource);
// give it the JSON
buf.insert(0, "parse-json(");
buf.append(")");
Object json = xPathCompiler.evaluate(buf.toString(), xmlRootNode);
System.out.println("JSON read in!!! json = " + json);
}
}
If you have a Java String with JSON pass it in as a variable to XPath and call parse-json on the variable:
Processor processor = new Processor(true);
String[] jsonExamples = { "1", "true", "null", "\"string\"", "[1,2,3]", "{ \"prop\" : \"value\" }" };
XPathCompiler compiler = processor.newXPathCompiler();
compiler.declareVariable(new QName("json"));
XPathExecutable executable = compiler.compile("parse-json($json)");
XPathSelector selector = executable.load();
for (String json : jsonExamples) {
selector.setVariable(new QName("json"), new XdmAtomicValue(json));
XdmValue value = selector.evaluate();
System.out.println(value);
}
If you have a file with JSON pass its file name or in general URI as a variable to XPath and call json-doc (https://www.w3.org/TR/xpath-functions/#func-json-doc) on the variable:
compiler = processor.newXPathCompiler();
compiler.declareVariable(new QName("json-uri"));
executable = compiler.compile("json-doc($json-uri)");
selector = executable.load();
selector.setVariable(new QName("json-uri"), new XdmAtomicValue("example1.json")); // pass in a relative (e.g. 'example.json' or 'subdir/example.json') or an absolute URI (e.g. 'file:///C:/dir/subdir/example.json' or 'http://example.com/example.json') here, not an OS specific file path
XdmValue value = selector.evaluate();
System.out.println(value);
Of course you can separate the steps and parse a string to an XdmValue or a file to an XdmValue and then pass it in later as a variable to another XPath evaluation.
So lets assume you have employees.json containing
{
"employees": [
{
"name": "mike",
"department": "accounting",
"age": 34
},
{
"name": "sally",
"department": "sales",
"age": 24
}
]
}
then you can parse it with the second sample into an XdmValue value and use that further as a context item for an expression e.g
avg(?employees?*?age)
would compute the average age:
Processor processor = new Processor(true);
XPathCompiler compiler = processor.newXPathCompiler();
compiler.declareVariable(new QName("json-uri"));
XPathExecutable executable = compiler.compile("json-doc($json-uri)");
XPathSelector selector = executable.load();
selector.setVariable(new QName("json-uri"), new XdmAtomicValue("employees.json"));
XdmValue value = selector.evaluate();
System.out.println(value);
executable = compiler.compile("avg(?employees?*?age)");
selector = executable.load();
selector.setContextItem((XdmItem) value);
XdmItem result = selector.evaluateSingle();
System.out.println(result);
At https://xqueryfiddle.liberty-development.net/94hwphZ I have another sample processing JSON, it also computes the average of a value with an expression using the lookup operator ?, first with ?Students to select the Students item of the context map, then with an asterisk ?* on the returned array to get a sequence of all array items, finally with ?Grade to select the Grade value of each array item:
avg(?Students?*!(?Grade, 70)[1])
but with the additional requirement to select a default of 70 for those objects/maps that don't have a Grade. The sample JSON is
{
"Class Name": "Science",
"Teacher\u0027s Name": "Jane",
"Semester": "2019-01-01",
"Students": [
{
"Name": "John",
"Grade": 94.3
},
{
"Name": "James",
"Grade": 81.0
},
{
"Name": "Julia",
"Grade": 91.9
},
{
"Name": "Jessica",
"Grade": 72.4
},
{
"Name": "Johnathan"
}
],
"Final": true
}
The fiddle supports XQuery 3.1 but like for XPath 3.1 the JSON is passed in as a variable and then parsed with parse-json into an XDM item to serve as the context item for further evaluation.
To give some examples of more complex XPath 3.1 expressions against JSON I have taken the JSON sample from the path examples in https://github.com/json-path/JsonPath as the JSON input to parse-json (if you have a string) or json-doc if you have a URI to a file or even a HTTP(S) location and used it as the context item for some paths (evaluated in the fiddle as XQuery 3.1 but XPath 3.1 is a subset and I think I have restricted the samples to XPath 3.1:
The samples are at:
https://xqueryfiddle.liberty-development.net/gWmuPs6/0 : ?store?book?*?author : "the authors of all books"
https://xqueryfiddle.liberty-development.net/gWmuPs6/1 : ?store?* : "all things in the store, both books and bicycles"
https://xqueryfiddle.liberty-development.net/gWmuPs6/2 : ?store?book?3 : "the third book"
https://xqueryfiddle.liberty-development.net/gWmuPs6/3 : ?store?book?(1,2) : "the first two books"
https://xqueryfiddle.liberty-development.net/gWmuPs6/4 : ?store?book?*[?isbn] : "all books with an isbn number"
https://xqueryfiddle.liberty-development.net/gWmuPs6/5 : ?store?book?*[?price < 10] : "all books with a price less than 10"
https://xqueryfiddle.liberty-development.net/gWmuPs6/6 : let $context := . return ?store?book?*[?price <= $context?expensive] : "all books with a price less than expensive"
https://xqueryfiddle.liberty-development.net/gWmuPs6/7 : count(?store?book?*) : "the number of books"
The file is
{
"store": {
"book": [
{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{
"category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{
"category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
},
"expensive": 10
}

referencing objects in JSON

I have a code as a shown below in which I am not sure how to do referencing.
<p id="demo" ></p>
<p id="options"></p>
<script>
var myObj, myJSON, text, obj;
myObj = {
"quiz": {
"sport": {
"q1": {
"question": "Which one is correct team name in NBA?",
"options": [
"New York Bulls",
"Los Angeles Kings",
"Golden State Warriros",
"Huston Rocket"
],
"answer": "Huston Rocket"
}
},
"maths": {
"q1": {
"question": "5 + 7 = ?",
"options": [
"10",
"11",
"12",
"13"
],
"answer": "12"
}
}
}
}
//Storing data:
// converting JS object into String
myJSON = JSON.stringify(myObj);
localStorage.setItem("testJSON", myJSON);
//Retrieving data:
text = localStorage.getItem("testJSON");
//converting String into JS object
obj = JSON.parse(text);
document.getElementById("demo").innerHTML = // code
Problem Statement:
I am wondering what changes should I make in the below line(which is the last line in the above code) so that the output should be Huston Rocket.
document.getElementById("demo").innerHTML = // code
I tried in the following way but somehow I am not able to reach Huston Rocket
document.getElementById("demo").innerHTML = myObj.quiz.sport.q1.answer;
You are using incorrect name, after Json parsing, your Json object is 'obj'
So use it as
document.getElementById("demo").innerHTML = obj.quiz.sport.q1.answer;

Dynamically Parsing JSON with Groovy

I have a JSON document pulled back from a support system API. With my code, I want to pull out the pre-configured fields dynamically, presuming that the JSON may have more or fewer of the desired fields when my program calls the API.
I have some code that works, though it seems very convoluted and inefficient.
Here is a snippet of the pieces of JSON that I'm interested in:
{
"rows": [
{
"assignee_id": 1,
"created": "2017-01-25T14:13:19Z",
"custom_fields": [],
"fields": [],
"group_id": 2468,
"priority": "Low",
"requester_id": 2,
"status": "Open",
"subject": "Support request",
"ticket": {
"description": "Ticket descritpion",
"id": 1000,
"last_comment": {
"author_id": 2,
"body": "Arbitrary text",
"created_at": "2017-02-09T14:21:38Z",
"public": false
},
"priority": "low",
"status": "open",
"subject": "Support request",
"type": "incident",
"url": "Arbitrary URL"
},
"updated": "2017-02-09T14:21:38Z",
"updated_by_type": "Agent"
},
{
"assignee_id": 1,
"created": "2017-02-09T14:00:18Z",
"custom_fields": [],
"fields": [],
"group_id": 3579,
"priority": "Normal",
"requester_id": 15,
"status": "Open",
"subject": "Change request",
"ticket": {
"description": "I want to change this...",
"id": 1001,
"last_comment": {
"author_id": 20,
"body": "I want to change the CSS on my website",
"created_at": "2017-02-09T14:12:12Z",
"public": true
},
"priority": "normal",
"status": "open",
"subject": "Change request",
"type": "incident",
"url": "Arbitrary URL"
},
"updated": "2017-02-09T14:12:12Z",
"updated_by_type": "Agent"
}
]
}
I have an ArrayList called wantedFields that I build up from a config to define which information I want to pull out from the JSON:
["id","subject","requester_id","status","priority","updated","url"]
The complexity is that data is replicated in the API, and I only want to pull out data once, with a preference for the data in "rows" where applicable. My method for doing this is below. It feels like I'm repeating code but I can't really see how to make this work more efficiently. The JSON is held as "viewAsJson".
def ArrayList<Map<String,Object>> assignConfiguredFields(viewAsJson, wantedFields) {
//Pull out configured fields from JSON and store as Map to write as CSV later
ArrayList<Map<String,Object>> listOfDataToWrite = new ArrayList<Map<String,Object>>()
ArrayList<String> rowKeyList = new ArrayList<String>()
def validationRow = viewAsJson.rows.get(0)
//Compare one row object to config first
validationRow.each { k, v ->
if (wantedFields.contains(k)) {
wantedFields.remove(k)
rowKeyList.add(k)
}
}
ArrayList<String> ticketKeyList = new ArrayList<String>()
def validationTicket = viewAsJson.rows.ticket.get(0)
//Compare one ticket object to config first
validationTicket.each { k, v ->
if (wantedFields.contains(k)) {
wantedFields.remove(k)
ticketKeyList.add(k)
}
}
def rows = viewAsJson.rows
def tickets = viewAsJson.rows.ticket
//Pull matching ticket objects from JSON and store in Map
ArrayList<Map<String,Object>> tickList= new ArrayList<>()
ArrayList<Map<String,Object>> rowList= new ArrayList<>()
rows.each { row ->
Map<String,Object> rowMap = new HashMap<>()
row.each { k, v ->
if(rowKeyList.contains(k))
rowMap.put(k,v)
}
rowList.add(rowMap)
}
tickets.each { ticket ->
Map<String,Object> ticketMap = new HashMap<>()
ticket.each { k, v ->
if(ticketKeyList.contains(k))
ticketMap.put(k, v)
}
tickList.add(ticketMap)
}
for (int i = 0; i < rowList.size(); i++) {
HashMap<String,Object> dataMap = new HashMap<>()
dataMap.putAll(rowList.get(i))
dataMap.putAll(tickList.get(i))
listOfDataToWrite.add(dataMap)
}
println listOfDataToWrite
return listOfDataToWrite
}
I know there should be some validation for if the wantedFields ArrayList is still populated. I've iterated on this code so many times I just forgot to re-add that this time.
I don't know if you still need this code but why not try something like this.
Have a translation map and run each row through it.
Object tranverseMapForValue(Map source, String keysToTranverse, Integer location = 0){
List keysToTranverseList = keysToTranverse.split(/\./)
tranverseMapForValue(source, keysToTranverseList, location)
}
Object tranverseMapForValue(Map source, List keysToTranverse, Integer location = 0){
if(source.isEmpty() || keysToTranverse.isEmpty()){
return null
}
String key = keysToTranverse[location]
if(source[key] instanceof Map){
return tranverseMapForValue(source[key], keysToTranverse, location + 1)
}
else{
return source[key]
}
}
Map translation = [
"ticket.id": "id",
"ticket.subject": "subject",
"requester_id": "requester_id",
"ticket.status": "status",
"priority": "priority",
"updated": "updated",
"ticket.url": "url"
]
List rows = []
json.rows.each{ row ->
Map mapForRow = [:]
translation.each{ sourceKey, newKey ->
mapForRow << [(newKey): tranverseMapForValue(row, sourceKey)]
}
rows.add(mapForRow)
}

How to persist an array using Realm Swift and ObjectMapper?

I get an error when I try to save an array that comes from a JSON string. I've tried to use RLMArray with no success.
The error I receive is:
'RLMException', reason: 'Property 'page' is of type 'RLMArray<(null)>' which is not a supported RLMArray object type.
My model class:
public class Project: Object, Mappable {
dynamic var id = 0
dynamic var user: User!
dynamic var page: RLMArray!
dynamic var error_message: String! = ""
dynamic var status: String! = ""
override public static func primaryKey() -> String? {
return "id"
}
required convenience public init?(_ map: Map) {
self.init()
mapping(map)
}
public func mapping(map: Map) {
user <- map["user"]
page <- map["page"]
error_message <- map["error_message"]
status <- map["status"]
}
}
JSON File:
let parameters = [
"user": [
"username": "Marcus",
"password": "123asd"
],
"page": [
"home": [
[
"kind": "navigation",
"title": "suite",
"image": "ic_suite",
"backgroundImage": "ic_background1"
],
[
"kind": "navigation",
"title": "jardim",
"image": "ic_jardim",
"backgroundImage": "ic_background2"
]
],
"suite": [
[
"kind": "button",
"title": "My Master Suite",
"textColor": "0x000000",
"textSize": "16"
]
]
],
"status": "success",
"error_message": ""
]
self.project = Mapper<Project>().map(parameters)
Your class inherits from Object, Realm Swift's base class, but is attempting to use RLMArray, a Realm Objective-C type, in its interface. You cannot mix Realm Swift and Realm Objective-C in this manner. You should use List<T> for array properties when using Realm Swift.

Swift JSON Parsing - Unable to access field/returns nil

I'm using Google's geolocator API to map some stuff automatically. It returns a JSON string in the request, but I'm having a lot of difficulty parsing it. I've tried things like Freddy and SwiftyJSON but can't get either to extract the field I want.
Here's a sample of my code:
func sendJsonRequest(ConnectionString: String,
HTTPMethod : HttpMethod = HttpMethod.Get,
JsonHeaders : [String : String] = [ : ],
JsonString: String = "") -> NSData? {
// create the request & response
let request = NSMutableURLRequest(URL: NSURL(string: ConnectionString)!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 5)
// create some JSON data and configure the request
let jsonString = JsonString;
request.HTTPBody = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
// handle both get and post
request.HTTPMethod = HTTPMethod.rawValue
// we'll always be sending json so this is fine
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
// add the headers. If there aren't any then that's ok
for item in JsonHeaders {
request.addValue(item.1, forHTTPHeaderField: item.0)
}
print("Request:")
print(request)
let session = NSURLSession.sharedSession()
var data : NSData?
var urlTask = session.dataTaskWithRequest(request) { (Data, Response, Error) in
data = Data
}
urlTask.resume()
while (data == nil) {
}
return data
}
// return the coordinates of a given location
func getCoordinates() -> Coordinates {
var result = Coordinates()
let ConnectionString = "https://maps.googleapis.com/maps/api/geocode/json?address=43201"
let jsondata = sendJsonRequest(ConnectionString)
let data = jsondata
let json = JSON(data!)
print(json)
return result
}
getCoordinates()
Here's an example of the output I'm getting from a separate JSON client:
{
"results": [
{
"address_components": [
{
"long_name": "43201",
"short_name": "43201",
"types": [
"postal_code"
]
},
{
"long_name": "Columbus",
"short_name": "Columbus",
"types": [
"locality",
"political"
]
},
{
"long_name": "Franklin County",
"short_name": "Franklin County",
"types": [
"administrative_area_level_2",
"political"
]
},
{
"long_name": "Ohio",
"short_name": "OH",
"types": [
"administrative_area_level_1",
"political"
]
},
{
"long_name": "United States",
"short_name": "US",
"types": [
"country",
"political"
]
}
],
"formatted_address": "Columbus, OH 43201, USA",
"geometry": {
"bounds": {
"northeast": {
"lat": 40.011147,
"lng": -82.9723898
},
"southwest": {
"lat": 39.976962,
"lng": -83.0250691
}
},
"location": {
"lat": 39.9929821,
"lng": -83.00122100000002
},
"location_type": "APPROXIMATE",
"viewport": {
"northeast": {
"lat": 40.011147,
"lng": -82.9723898
},
"southwest": {
"lat": 39.976962,
"lng": -83.0250691
}
}
},
"place_id": "ChIJ9Rz24rWOOIgR3EEuL2Ge4oo",
"types": [
"postal_code"
]
}
],
"status": "OK"
}
I'm trying to get the field results.geometry.location. Using the Freddy JSON parsing library I was able to get the results field but I couldn't access the geometry field. Can someone take a look at this to see if I'm doing something wrong? SwiftyJSON doesn't even let me parse the JSON.
The closure passed as an argument in dataTaskWithRequest is asynchronous meaning that it could be called instantly or way down the road given network conditions. It would be better to pass a closure in your original sendJsonRequest method while return void. Once the dataTaskWithResult closure is called, you can invoke your closure with the response.
In terms of code, it might look like this:
func sendJsonRequest(connectionString: String,
httpMethod : HttpMethod = HttpMethod.Get,
jsonHeaders : [String : String] = [ : ],
jsonString: String = "",
completion: (data: NSData?, error: NSError?) -> Void) {
… //Your code
var urlTask = session.dataTaskWithRequest(request) { (optionalData, optionalResponse, optionalError) in
NSOperationQueue.mainQueue().addOperation {
if let data = optionalData {
completion(data, nil)
}
else if let error = optionalError {
completion(nil, error)
}
}
}
urlTask.resume()
}
// return the coordinates of a given location
func getCoordinates(withCompletion completion: (Coordinates) -> Void) {
let connectionString = "https://maps.googleapis.com/maps/api/geocode/json?address=43201"
sendJsonRequest(connectionString: connectionString) {
(optionalData, optionalError) in
if let data = optionalData {
let json = JSON(data)
print(json)
//Do your conversion to Coordinates here
let coordinates = //?
completion(coordinates)
}
// Handle errors, etc…
}
}
One note, arguments and variables are lowercased. Only class names should be uppercase.
It's a javascript object, you can do the below to retrive information
Assign the result to a variable
var results = {
"results": [
{
"address_components": [
{
"long_name": "43201",
"short_name": "43201",
"types": [
"postal_code"
]
},
{
"long_name": "Columbus",
"short_name": "Columbus",
"types": [
"locality",
"political"
]
},
{
"long_name": "Franklin County",
"short_name": "Franklin County",
"types": [
"administrative_area_level_2",
"political"
]
},
{
"long_name": "Ohio",
"short_name": "OH",
"types": [
"administrative_area_level_1",
"political"
]
},
{
"long_name": "United States",
"short_name": "US",
"types": [
"country",
"political"
]
}
],
"formatted_address": "Columbus, OH 43201, USA",
"geometry": {
"bounds": {
"northeast": {
"lat": 40.011147,
"lng": -82.9723898
},
"southwest": {
"lat": 39.976962,
"lng": -83.0250691
}
},
"location": {
"lat": 39.9929821,
"lng": -83.00122100000002
},
"location_type": "APPROXIMATE",
"viewport": {
"northeast": {
"lat": 40.011147,
"lng": -82.9723898
},
"southwest": {
"lat": 39.976962,
"lng": -83.0250691
}
}
},
"place_id": "ChIJ9Rz24rWOOIgR3EEuL2Ge4oo",
"types": [
"postal_code"
]
}
],
"status": "OK"
};
console.log(results); // you can see the object
Object {results: Array[1], status: "OK"}
console.log(results.results[0]); // Accessing the first object inside the array
Object {address_components: Array[5], formatted_address: "Columbus, OH 43201, USA", geometry: Object, place_id: "ChIJ9Rz24rWOOIgR3EEuL2Ge4oo", types: Array[1]}
console.log(results.results[0].geometry); // Accessing the geometry object.
Object {bounds: Object, location: Object, location_type: "APPROXIMATE", viewport: Object}
you can use JSON.stringify to make it simple.
I got my code to work with the Freddy JSON library. Here's my new code, in case anyone runs into a similar issue:
func getCoordinates(address: String) -> Coordinates {
var result = Coordinates()
let ConnectionString = _connectionUrl + address
let jsondata = sendJsonRequest(ConnectionString)
//print(json)
// returns a [string : AnyObject]
let data = jsondata
do {
let json = try JSON(data: data!)
let results = try json.array("results")[0]
let geometry = try results.dictionary("geometry")
print(geometry)
let location = geometry["location"]!
print(location)
let lat = try location.double("lat")
let lng = try location.double("lng")
result.Latitude = lat
result.Longitude = lng
} catch {
let nsError = error as NSError
print(nsError.localizedDescription)
}
}