create json array in swift alamofire - ios

Here is the request format that server requires ,
{
"internal_name": "SDSSD",
"display_name": "SDSDSDSD",
"image": "sesse.jpg",
"notes": "sdsdsdsdsdsdsdsd",
"short_description": "ssdsdsd",
"long_description": "sdsdsdsd",
"ean_code": "3434343434",
"status": "not_verified",
"state": "active",
"quantity": 1,
"brand": {
“name”: “My Brand”
},
"categories": [
{
“id”: “My Category”
}
]
}
In here , as you can see , it requires , categories as an array , so my question is how can i create an array . using swift . here is my swift code
let parameters :[String:AnyObject] = [
"internal_name":product.displayName,
"display_name":product.displayName,
"language":Constant.Language.LAN_ENGLISH,
"notes":product.initialName,
"image": product.photo,
"short_description":product.longDescription,
"long_description":product.longDescription,
"ean_code":product.eanCode,
"status":product.status,
"state":Constant.Status.STATUS_ACTIVE,
"categories": [
"id":product.categoryObject.id
],
"quantity":1,
]
this doesnt accept from the server since its not an array , what am i missing here

Try below code :
let parameters :Parameters = [
"internal_name":product.displayName,
"display_name":product.displayName,
"language":Constant.Language.LAN_ENGLISH,
"notes":product.initialName,
"image": product.photo,
"short_description":product.longDescription,
"long_description":product.longDescription,
"ean_code":product.eanCode,
"status":product.status,
"state":Constant.Status.STATUS_ACTIVE,
"brand" : ["name" : "My Brand"],
"categories": [
["id":product.categoryObject.id]
],
"quantity":1,
]

Related

Issue with fetching a custom tileset from CARTO and displaying it on a MapBox map iOS Swift

I'm attempting to fetch a custom tileset from CARTO using the documentation I found that the way to fetch from the API doc is:
curl --location --request GET 'https://gcp-us-east1.api.carto.com/v3/maps/carto_dw/tileset?name=carto-demo-data.demo_tilesets.nasadem_glo_quadgrid15' --header 'Authorization: Bearer <your access token>'
I made that request on Swift as follows:
{
let urlString = "\(environment.apiBaseURL)/v3/maps/\(environment.connection)/tileset"
return Future<CartoTileJsonResponse, Error> { [weak self] promise in
self?.session
.request(urlString,
method: .get,
parameters: ["name": tileSetName]
)
.validate()
.responseData(completionHandler: { response in
if let error = response.error {
promise(.failure(error))
return
}
guard let data = response.value else {
promise(.failure(response.error ?? NSError(domain: "unknow error", code: 999, userInfo: nil)))
return
}
do {
let cartoTileJsonResponse = try JSONDecoder().decode(CartoTileJsonResponse.self, from: data)
promise(.success(cartoTileJsonResponse))
} catch(let error) {
debugPrint(error)
promise(.failure(error))
}
})
}
}
As the name of the function says this return a new URL which I also make a GET request which finally returns a tilejson as shown:
{
"name": "NiallsFarm_Tileset_1_NDVI",
"tilejson": "3.1.0",
"center": [
-2.637422918924969,
55.96538584577466,
15
],
"description": "",
"maxzoom": 15,
"tilestats": {
"layers": [
{
"layer": "default",
"attributeCount": 2,
"count": 22146,
"geometry": "Polygon",
"attributes": [
{
"type": "String",
"attribute": "fieldName",
"categories": [
{
"category": "South Tempriggs",
"frequency": 7587
},
{
"category": "Kirklands",
"frequency": 6603
},
{
"category": "East Lothian",
"frequency": 4677
},
{
"category": "Crumstanes",
"frequency": 3279
}
]
},
{
"quantiles": {
"3": [
0.5691,
0.658
],
"4": [
0.5328,
0.6307,
0.6627
],
"5": [
0.5112,
0.5942,
0.6515,
0.6658
],
"6": [
0.5004,
0.5699,
0.6307,
0.6578,
0.6675
],
"7": [
0.4899,
0.5509,
0.6055,
0.6464,
0.6604,
0.6689
],
"8": [
0.4824,
0.5344,
0.5841,
0.6303,
0.6545,
0.6627,
0.6697
],
"9": [
0.4768,
0.5212,
0.5705,
0.6123,
0.6436,
0.6576,
0.6646,
0.6705
],
"10": [
0.4708,
0.5112,
0.5574,
0.5937,
0.6303,
0.6516,
0.6596,
0.6657,
0.6712
],
"11": [
0.4674,
0.504,
0.5447,
0.5801,
0.6151,
0.6413,
0.6555,
0.6613,
0.6666,
0.6718
],
"13": [
0.4594,
0.4931,
0.5235,
0.5607,
0.5872,
0.617,
0.6401,
0.6534,
0.6591,
0.6641,
0.6682,
0.6726
],
"14": [
0.4542,
0.4899,
0.5164,
0.5502,
0.5779,
0.6048,
0.6303,
0.6468,
0.6559,
0.6606,
0.665,
0.6688,
0.6731
],
"15": [
0.4514,
0.4866,
0.5112,
0.541,
0.5705,
0.5937,
0.6192,
0.6387,
0.6516,
0.6576,
0.6617,
0.6657,
0.6693,
0.6732
],
"16": [
0.4496,
0.4824,
0.5052,
0.5344,
0.5626,
0.5841,
0.6089,
0.6303,
0.6448,
0.6545,
0.6588,
0.6627,
0.6663,
0.6697,
0.6736
],
"17": [
0.4451,
0.4792,
0.5026,
0.5263,
0.5538,
0.5767,
0.5977,
0.6207,
0.6381,
0.6504,
0.6562,
0.66,
0.6637,
0.6669,
0.6702,
0.6738
],
"18": [
0.4417,
0.476,
0.499,
0.521,
0.547,
0.571,
0.5885,
0.612,
0.6304,
0.6434,
0.6531,
0.6578,
0.6609,
0.6646,
0.6675,
0.6706,
0.674
],
"19": [
0.4394,
0.4729,
0.4952,
0.5154,
0.5407,
0.5643,
0.5821,
0.6018,
0.6226,
0.6372,
0.6483,
0.6551,
0.6587,
0.662,
0.6653,
0.668,
0.6709,
0.6742
],
"20": [
0.4366,
0.4708,
0.4921,
0.5112,
0.5341,
0.5575,
0.576,
0.5941,
0.6135,
0.6304,
0.6423,
0.6521,
0.6564,
0.6596,
0.6627,
0.6658,
0.6684,
0.6712,
0.6744
],
"12We ": [
0.4622,
0.4983,
0.5344,
0.5705,
0.6005,
0.6303,
0.649,
0.6576,
0.6627,
0.6675,
0.6722
]
},
"attribute": "NDVI",
"min": 0.2076,
"avg": 0.5944896234082888,
"type": "Number",
"max": 0.6885,
"sum": "13165.56719999999999590190036258263717172608"
}
]
}
],
"layerCount": 1
},
"tiles": [
"https://gcp-us-east1.api.carto.com/v3/maps/omegacrop-production/tileset/{z}/{x}/{y}?name={NAME}&partition=12_15_16142_16145_10208_10211_3999_1&formatTiles=mvt&cache=1653383237150&access_token={ACCES_TOKEN}"
],
"minzoom": 12,
"attribution": "",
"bounds": [
-2.6481308960412906,
55.9604080548856,
-2.62664091461468,
55.97227003506276
],
"vector_layers": [
{
"field": {
"fieldName": "String",
"NDVI": "Number"
},
"id": "default",
"minzoom": 12,
"geometry_type": "Polygon",
"maxzoom": 15
}
]
}
Which I'm not being able to display on Mapbox Map using either Raster or Vector Layers. Also when trying to do a GET request from the tiles url the tilejson return I'm receiving the following error:
{
"error": "invalid zoom value, must be an integer number greater than or equal to 0",
"status": 400,
"message": "invalid zoom value, must be an integer number greater than or equal to 0",
"z": null,
"x": null,
"y": null
}
If anyone have experienced this or may know what I may be doing wrong it would be highly appreciated.

Only able to parse SOME of JSON data, syntax issue?

I'm having an issue parsing some of the JSON data being retrieved from Oxford Dictionaries into my application.
I am printing the JSON response into my console which confirms that I am successfully getting the data needed.
Verification that JSON data is being retrieved:
There are two main folders initially when I get the JSON data back. "results", which contains the information I need: the word definition and other information
and "metadata".
JSON format that I am getting back from Oxford Dictionary:
I am able to parse the information contained in the "metadata" folder, and have printed it into the console to confirm.
Verification that I am able to parse and print the metadata:
I however, can't seem to parse any of the data contained in the 'Results' folder, which is what I actually need. The definition, the language, the word ID, et cetera.
What am I doing wrong here??
Example of issue with parsing "results" data:
Another example of faulty attempt to parse 'results':
Plain text copy of my JSON response:
{
"metadata": {
"provider": "Oxford University Press"
},
"results": [
{
"id": "ace",
"language": "en",
"lexicalEntries": [
{
"entries": [
{
"etymologies": [
"Middle English (denoting the ‘one’ on dice): via Old French from Latin as ‘unity, a unit’"
],
"grammaticalFeatures": [
{
"text": "Singular",
"type": "Number"
}
],
"homographNumber": "100",
"senses": [
{
"definitions": [
"a playing card with a single spot on it, ranked as the highest card in its suit in most card games"
],
"domains": [
"Cards"
],
"examples": [
{
"registers": [
"figurative"
],
"text": "life had started dealing him aces again"
},
{
"text": "the ace of diamonds"
}
],
"id": "m_en_gbus0005680.006",
"short_definitions": [
"playing card with single spot on it, ranked as highest card in its suit in most card games"
]
},
{
"definitions": [
"a person who excels at a particular sport or other activity"
],
"domains": [
"Sport"
],
"examples": [
{
"text": "a motorcycle ace"
}
],
"id": "m_en_gbus0005680.010",
"registers": [
"informal"
],
"short_definitions": [
"person who excels at particular sport or other activity"
],
"subsenses": [
{
"definitions": [
"a pilot who has shot down many enemy aircraft"
],
"domains": [
"Air Force"
],
"examples": [
{
"text": "a Battle of Britain ace"
}
],
"id": "m_en_gbus0005680.011",
"short_definitions": [
"pilot who has shot down many enemy aircraft"
]
}
],
"thesaurusLinks": [
{
"entry_id": "ace",
"sense_id": "t_en_gb0000173.001"
}
]
},
{
"definitions": [
"(in tennis and similar games) a service that an opponent is unable to return and thus wins a point"
],
"domains": [
"Tennis"
],
"examples": [
{
"text": "Nadal banged down eight aces in the set"
}
],
"id": "m_en_gbus0005680.013",
"short_definitions": [
"(in tennis and similar games) service that opponent is unable to return and thus wins point"
],
"subsenses": [
{
"definitions": [
"a hole in one"
],
"domains": [
"Golf"
],
"examples": [
{
"text": "his hole in one at the 15th was Senior's second ace as a professional"
}
],
"id": "m_en_gbus0005680.014",
"registers": [
"informal"
],
"short_definitions": [
"hole in one"
]
}
]
}
]
},
{
"etymologies": [
"early 21st century: abbreviation of asexual, with alteration of spelling on the model of ace"
],
"grammaticalFeatures": [
{
"text": "Singular",
"type": "Number"
}
],
"homographNumber": "200",
"senses": [
{
"definitions": [
"a person who has no sexual feelings or desires"
],
"domains": [
"Sex"
],
"examples": [
{
"text": "both asexual, they have managed to connect with other aces offline"
}
],
"id": "m_en_gbus1190638.004",
"short_definitions": [
"asexual person"
]
}
]
}
],
"language": "en",
"lexicalCategory": "Noun",
"pronunciations": [
{
"audioFile": "http://audio.oxforddictionaries.com/en/mp3/ace_1_gb_1_abbr.mp3",
"dialects": [
"British English"
],
"phoneticNotation": "IPA",
"phoneticSpelling": "eɪs"
}
],
"text": "ace"
},
{
"entries": [
{
"grammaticalFeatures": [
{
"text": "Positive",
"type": "Degree"
}
],
"homographNumber": "101",
"senses": [
{
"definitions": [
"very good"
],
"examples": [
{
"text": "Ace! You've done it!"
},
{
"text": "an ace swimmer"
}
],
"id": "m_en_gbus0005680.016",
"registers": [
"informal"
],
"short_definitions": [
"very good"
],
"thesaurusLinks": [
{
"entry_id": "ace",
"sense_id": "t_en_gb0000173.002"
}
]
}
]
},
{
"grammaticalFeatures": [
{
"text": "Positive",
"type": "Degree"
}
],
"homographNumber": "201",
"senses": [
{
"definitions": [
"(of a person) having no sexual feelings or desires; asexual"
],
"domains": [
"Sex"
],
"examples": [
{
"text": "I didn't realize that I was ace for a long time"
}
],
"id": "m_en_gbus1190638.006",
"short_definitions": [
"asexual"
]
}
]
}
],
"language": "en",
"lexicalCategory": "Adjective",
"pronunciations": [
{
"audioFile": "http://audio.oxforddictionaries.com/en/mp3/ace_1_gb_1_abbr.mp3",
"dialects": [
"British English"
],
"phoneticNotation": "IPA",
"phoneticSpelling": "eɪs"
}
],
"text": "ace"
},
{
"entries": [
{
"grammaticalFeatures": [
{
"text": "Transitive",
"type": "Subcategorization"
},
{
"text": "Present",
"type": "Tense"
}
],
"homographNumber": "102",
"senses": [
{
"definitions": [
"(in tennis and similar games) serve an ace against (an opponent)"
],
"domains": [
"Tennis"
],
"examples": [
{
"text": "he can ace opponents with serves of no more than 62 mph"
}
],
"id": "m_en_gbus0005680.020",
"registers": [
"informal"
],
"short_definitions": [
"(in tennis and similar games) serve ace against"
],
"subsenses": [
{
"definitions": [
"score an ace on (a hole) or with (a shot)"
],
"domains": [
"Golf"
],
"examples": [
{
"text": "there was a prize for the first player to ace the hole"
}
],
"id": "m_en_gbus0005680.026",
"short_definitions": [
"score ace on hole or with"
]
}
]
},
{
"definitions": [
"achieve high marks in (a test or exam)"
],
"examples": [
{
"text": "I aced my grammar test"
}
],
"id": "m_en_gbus0005680.028",
"regions": [
"North American"
],
"registers": [
"informal"
],
"short_definitions": [
"achieve high marks in"
],
"subsenses": [
{
"definitions": [
"outdo someone in a competitive situation"
],
"examples": [
{
"text": "the magazine won an award, acing out its rivals"
}
],
"id": "m_en_gbus0005680.029",
"notes": [
{
"text": "\"ace someone out\"",
"type": "wordFormNote"
}
],
"short_definitions": [
"outdo someone in competitive situation"
]
}
]
}
]
}
],
"language": "en",
"lexicalCategory": "Verb",
"pronunciations": [
{
"audioFile": "http://audio.oxforddictionaries.com/en/mp3/ace_1_gb_1_abbr.mp3",
"dialects": [
"British English"
],
"phoneticNotation": "IPA",
"phoneticSpelling": "eɪs"
}
],
"text": "ace"
}
],
"type": "headword",
"word": "ace"
}
]
}
Retrieve results like this:
let results = json["results"][0]["id"]
Or
if let resultObj = json["results"].first {
let id = resultObj["id"]
}
id key is in the dictionary which is at zero index of results array.

$ dont work with JsonPath

I Post one Json with RestAssured and After I need to verify that all fields are stored in the database with the correct values.My Json is :
{
"id": "1",
"name": "name1",
"description": "description1",
"source": "source1",
"target": "target1",
"domain": "PM",
"transformation_rules": [
{
"name": "name2",
"filters": [
{
"object": "object1",
"pattern": "pattern1"
}
],
"operations": [
{
"pattern": "pattern2",
"replacement": "replacement1"
}
]
},
{
"name": "name3",
"filters": [
{
"object": "object2",
"pattern": "pattern2"
}
],
"operations": [
{
"pattern": "pattern3",
"replacement": "replacement2"
},
{
"pattern": "pattern3",
"replacement": "replacement3"
},
{
"pattern": "pattern4",
"replacement": "replacement4"
}
]
}
],
"conflict_policy": "ACCEPT_SOURCE"
}
So, I have :
responseGet = RestAssured.given().contentType(ContentType.JSON).when().get(urlApi + "/" + id);
My first verification is :
responseGet.then().body("$[0]['id']", equalTo("1"));
to verify that the field "id" equals to 1 it doesn't execute well and I change to :
responseGet.then().body("$.id", equalTo("1"));
and the same result ---> fails
Please, can you give me your suggestions for testing all the Json ?
Just for information, I try to apply : https://github.com/json-path/JsonPath.
Thank you very much in Advance,
Best Regards,
You can directly use jsonPath() for checking this:
For example:
responseGet.body().jsonPath().getString("id").equals("1");
For reading JsonPath

create a dictionary contains Array and Dictionary in swift 4

I just want to create an API JSON Structure. The following are the post body keys and objects. Are there any methods like object with keys and values similar to Objective C in Swift 4?
{
"name": "switch 1",
"type": "Switch",
"gatewayId":515,
"serialKey": "98:07:2D:48:D3:56",
"noOfGangs": 4,
"equipments": [
{
"name": "light",
"type": "Light",
"port": "1"
},
{
"name": "television",
"type": "Television",
"port": "3"
}
]
}
You can create the dictionary literally by annotating the type and replace the curly braces with square brackets
let dict : [String:Any] = ["name": "switch 1", "type": "Switch", "gatewayId":515, "serialKey": "98:07:2D:48:D3:56", "noOfGangs": 4, "equipments": [[ "name": "light", "type": "Light", "port": "1" ], ["name": "television", "type": "Television", "port": "3" ]]]
Or build it:
var dict : [String:Any] = ["name": "switch 1", "type": "Switch", "gatewayId":515, "serialKey": "98:07:2D:48:D3:56", "noOfGangs": 4]
var equipments = [[String:String]]()
equipments.append(["name": "light", "type": "Light", "port": "1" ])
equipments.append(["name": "television", "type": "Television", "port": "3" ])
dict["equipments"] = equipments
how to create Dictionary
var populatedDictionary = ["key1": "value1", "key2": "value2"]
this how to create Array
var shoppingList: [String] = ["Eggs", "Milk"]
you can create Dictionary by this type
var dictionary = [Int:String]()
dictionary.updateValue(value: "Hola", forKey: 1)
dictionary.updateValue(value: "Hello", forKey: 2)
dictionary.updateValue(value: "Aloha", forKey: 3)
// anather example
var dict = [ 1 : "abc", 2 : "cde"]
dict.updateValue("efg", forKey: 3)
print(dict)
your JSON
let dic :[String:Any] = ["name": "switch 1", "type": "Switch", "gatewayId":515, "serialKey": "98:07:2D:48:D3:56", "noOfGangs": 4, "equipments": [ [ "name": "light", "type": "Light", "port": "1" ],
[ "name": "television", "type": "Television", "port": "3" ] ] ]

Use Json_create always get NULL frome json-string in cocos2dx 2.2.3

My code at follow
CCLOG("info: %s",infoStr.c_str());
const char * buf=infoStr.c_str();
cocos2d::extension::Json* mJs = cocos2d::extension::Json_create(buf);
cocos2d::extension::Json* item = Json_getItem(mJs,"results");
cocos2d::extension::Json* array1 = Json_getItemAt (item, 0);
cocos2d::extension::Json* itemNode = Json_getItem(array1,"version");
float floatValue = itemNode->valuefloat;
CCLOG("floatValue: %f",floatValue);
The result of CCLOG("info: %s",infoStr.c_str()); is at follow:
{
"resultCount": 1,
"results": [
{
"kind": "software",
"features": [],
"supportedDevices": [
"iPhone4S",
"iPadWifi",
"iPadThirdGen4G",
"iPhone5",
"iPadMini4G",
"iPadFourthGen4G",
"iPodTouchThirdGen",
"iPadThirdGen",
"iPad3G",
"iPhone4",
"iPodTouchourthGen",
"iPodTouchFifthGen",
"iPhone-3GS",
"iPad2Wifi",
"iPhone5c",
"iPad23G",
"iPhone5s",
"iPadFourthGen",
"iPadMini"
],
"isGameCenterEnabled": false,
"screenshotUrls": [
"http://a5.mzstatic.com/us/r30/Purple/v4/52/c0/e5/52c0e504-3e37-80a8-f17a-0b49bff6e63b/screen1136x1136.jpeg",
"http://a4.mzstatic.com/us/r30/Purple6/v4/b6/8d/50/b68d500a-b84a-44fe-7fac-a055aa49e2ee/screen1136x1136.jpeg",
"http://a5.mzstatic.com/us/r30/Purple4/v4/30/80/ab/3080ab26-fa55-a69b-480d-a57c803f3b81/screen1136x1136.jpeg"
],
"ipadScreenshotUrls": [],
"artworkUrl60": "http://a288.phobos.apple.com/us/r30/Purple6/v4/e6/89/56/e689561d-2bbc-8769-4325-b2acd91e0cf9/AppIcon57x57.png",
"artworkUrl512": "http://a1062.phobos.apple.com/us/r30/Purple4/v4/1d/8c/2c/1d8c2c76-d441-4d3b-d43c-48e6f7aa98ad/mzl.oympcnqz.png",
"artistViewUrl": "https://itunes.apple.com/us/artist/wei-gao/id777399907?uo=4",
"artistId": 777399907,
"artistName": "wei gao",
"price": 0,
"version": "1.0",
"description": "description",
"currency": "USD",
"genres": [
"Photo & Video",
"Entertainment"
],
"genreIds": [
"6008",
"6016"
],
"releaseDate": "2014-01-02T23:19:32Z",
"sellerName": "w",
"bundleId": "D.IMyPhotos",
"trackId": 77,
"trackName": "ff",
"primaryGenreName": "Photo & Video",
"primaryGenreId": 6008,
"formattedPrice": "Free",
"wrapperType": "software",
"trackCensoredName": "ff",
"languageCodesISO2A": [
"EN"
],
"fileSizeBytes": "14",
"sellerUrl": "http://wwww",
"contentAdvisoryRating": "4+",
"artworkUrl100": "http://a1062.phobos.apple.com/us/r30/Purple4/v4/1d/8c/2c/1d8c2c76-d441-4d3b-d43c-48e6f7aa98ad/mzl.oympcnqz.png",
"trackViewUrl": "https://itunes.apple.com/us/app",
"trackContentRating": "4+"
}
]
}
I get Json* mJs always NULL.I think the string of json is right.I used google but can't get the answer.
Do i use Json_create in the wrong way? Or other reason? A lot of thank!

Resources