Sending Data to server in JSON format Swift - json

Server expecting from me data in JSON format . Like this ;
. Im trying to send data like this ;
func getProductListResponse(typeId : String , type : String) {
let tsoftFilter = [
"key" : type,
"value" : typeId
] as [String : AnyObject]
print("tsoft filter is \(tsoftFilter)")
let serviceParams = [
"store_id" : Config.productListId,
"page" : currentPage,
"per_page" : perPage,
"tsoft_filters" : "\(tsoftFilter)"
] as [String : AnyObject]
But it doesn't work where do I making mistake ?

You are adding the description of a dictionary which is not equal to JSON. And according to the screenshot you need even an array of dictionaries.
In this case it's easier to create the JSON literally
func getProductListResponse(typeId : String , type : String) {
let tsoftFilter = #"[{"key":"\(type)","value":"\(typeId)"}]"#
let serviceParams : [String : Any] = [
"store_id" : Config.productListId,
"page" : currentPage,
"per_page" : perPage,
"tsoft_filters" : tsoftFilter
]
...
By the way a parameter dictionary sent in a network request is never [String:AnyObject]

Try this:
let tsoftFilter = """
[
[ "key" : type, "value" : typeId]
]
"""

Related

Having trouble decoding retrieved JSON object in Swift

I am able to retrieve some JSON from an endpoint but then when I try to decode that JSON into my model object something goes wrong to where the json can't be parsed. I've made sure the properties in my model object matched the json keys, so I dont understand what the issue is. It prints out the catch block every time.
Here is my code to retrieve the json:
func getServiceProviders() {
let session = URLSession.shared
let url = URL(string: "http://exampleendpoint.com/example")!
URLSession.shared.dataTask(with: url) { data, response, error in
//Here is where I try to decode the json into my model object
do {
let jsonContent = try JSONDecoder().decode(ServiceObject.self, from: data!)
print(jsonContent)
} catch {
print("Ooops")
}
}.resume()
Here is my model object:
struct ServiceObject: Decodable {
let serviceproviders: [ServiceProvider]
struct ServiceProvider: Decodable {
let city: String
let coordinates: Location
let name: String
let overallGrade: String
let postalCode: Int
let state: String
let reviewCount: Int
}
struct Location: Decodable {
let latitude: Double
let longitude: Double
}
}
Here is what the json object I retrieve looks like:
{
"serviceproviders": [
{
"city" : "Beech Grove",
"coordinates" : {
"latitude" : "39.715417",
"longitude" : "-86.095646"
},
"name" : "William J Ciriello Plumbing Co Inc",
"overallGrade" : "A",
"postalCode" : "46107",
"state" : "Indiana",
"reviewCount" : 309
},
{
"city" : "Indianapolis",
"coordinates" : {
"latitude" : "39.922607",
"longitude" : "-86.0267094"
},
"name" : "Roby's Plumbing & Appliance Service",
"overallGrade" : "B",
"postalCode" : "46256",
"state" : "Indiana",
"reviewCount" : 903
},

How To Filter JSON data parser

JSON response
tranArr
[{
"total_amt" : -10000,
"tran_type" : "C3",
"pay_type" : "05",
"tran_time" : "20180125 133122",
"point_total" : 0
},
{
"total_amt" : -1004,
"tran_type" : "C5",
"pay_type" : "05",
"tran_time" : "20180124 163602",
"point_total" : 0
}]
=====================
I want to filter tran_type = "C3"
What should I do?
"total_amt" : -10000,
"tran_type" : "C3",
"pay_type" : "05",
"tran_time" : "20180125 133122",
"point_total" : 0
Try something like this:
let string = "[{ \"total_amt\" : -10000,\"tran_type\" : \"C3\", \"pay_type\" : \"05\", \"tran_time\" : \"20180125 133122\", \"point_total\" : 0},{\"total_amt\" : -1004,\"tran_type\" : \"C5\", \"pay_type\" : \"05\", \"tran_time\" : \"20180124 163602\", \"point_total\" : 0 }]"
// Convert string to Data
let jsonData = string.data(using: .utf8)!
do {
// Serialize the json Data and cast it into Array of Dictionary
let jsonObject = try JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) as? [[String: Any]]
// Apply filter on `tran_type`
let tranArr = jsonObject?.filter({ (dictionary) -> Bool in
dictionary["tran_type"] as? String == "C3"
})
print(tranArr)
} catch {
print(error)
}
Filtered result will be in tranArr object.

appending optional elements to an array from json in Swift

I have just started getting familiar with JSON. I have a class object that I am initialising by passing in a JSON. This object has an array that may be empty and I need to check it for value. so far I am trying:
init(json: JSON) {
id = json["id"].string
type = json["type"].string
text = json["text"].string
answer = json["answer"].string
format = json["format"].string
answeredBy = []
if let answeredByjson = json["answeredBy"].array {
for (_, userDict) in answeredByjson {
if let userDict = userDict as? [String : Any] {
answeredBy.append(JSON(User(dictionary: userDict)))
}
}
}
}
the elements in the array are dictionaries that have to be used to initialize another object (User).
the error I am getting is:
Expression type '[JSON]' is ambiguous without more context.
How can I update my code?
this is my json:
{
"answer" : "rachel",
"answeredBy" : {
"j1K4WXbOFRXfm3srk9oMtZJ8Iop2" : {
"email" : "an email",
"pictureURL" : "a URL",
"uid" : "j1K4WXbOFRXfm3srk9oMtZJ8Iop2",
"name" : "a name"
},
"vtYlmyerugedizHyOW6TV847Be23" : {
"email" : "an email",
"pictureURL" : "a URL",
"uid" : "vtYlmyerugedizHyOW6TV847Be23",
"name" : "Rusty Shakleford"
}
},
"format" : "field",
"id" : "1",
"type" : "text",
"text" : "In a foot race, Jerry was neither first nor last. Janet beat Jerry, Jerry beat Pat. Charlie was neither first nor last. Charlie beat Rachel. Pat beat Charlie. Who came in last?"
}
if let answeredByjson = json["answeredBy"].array {
...
}
produces an array [JSON], but you expect it to produce a dictionary [String: JSON]. That is why you receive:
Expression type '[JSON]' is ambiguous without more context
To produce a dictionary:
if let answeredByjson = json["answeredBy"].dictionary {
...
}
It you don't expect it to produce a dictionary [String: JSON] then this line doesn't make sense
for (_, userDict) in answeredByjson {

Query local JSON File in Swift [duplicate]

This question already has answers here:
Search through a large json file for a particular key value pair
(2 answers)
Closed 5 years ago.
I have a local JSON file that I am trying to parse based on a value. I can correctly get all the values from the file but what's the best solution to get a particular value. let say i have the following JSON data
[{ "city" : "AGAWAM", "loc" : [ -72.622739, 42.070206 ], "pop" : 15338,
"state" : "MA", "_id" : "01001" }
, { "city" : "CUSHMAN", "loc" : [ -72.51564999999999, 42.377017 ],
"pop"
: 36963, "state" : "MA", "_id" : "01002" }
, { "city" : "BARRE", "loc" : [ -72.10835400000001, 42.409698 ], "pop"
: 4546, "state" : "MA", "_id" : "01005" }]
Say I only want to show line with _id = 01002. What would be the best solution to achieve what I am asking? I added what I already have, any help would be greatly appreciated.
if let file = Bundle.main.url(forResource: "zip", withExtension: "json") {
do {
let data = try Data(contentsOf: file)
let json = JSON(data: data)
let jsonRecord = json["_id"]
print("this is json \(jsonRecord)")
} catch {
// handle error
}
}
found my answer using different terminology
here
Swift array version:
let peopleNamedTom = arrayOfPeople.filter { $0["Name"] == "Tom" }
SwiftyJSON array version:
let peopleNamedTom = arrayOfPeople.filter { $1["Name"] == "Tom" }

How to convert dictionary to json in Swift, and delete "optional" in json string

I want to convert a dictionary to json, dictionary as following:
[
[
"user_event" : "Optional({\n \"strokes\" : {\n \"oldText\" : \"er\",\n \"selection\" : \"error\",\n \"candidates\" : \"error|errors|era\",\n \"context\" : \"error \"\n }\n})",
"device_type" : "x86_64",
"language" : "EN_US"
],
[
"user_event" : "Optional({\n \"strokes\" : {\n \"oldText\" : \"\",\n \"selection\" : \"messages\",\n \"candidates\" : \"messages|message|in\",\n \"context\" : \"error messages \"\n }\n})",
"device_type" : "x86_64",
"language" : "EN_US"
]
]
I'm using following code:
let data = try NSJSONSerialization.dataWithJSONObject(object, options: NSJSONWritingOptions())
let json = NSString.init(data: data, encoding: NSUTF8StringEncoding)
But the results string has characters as "Optional(" which will cause the json decoder process fail, how can I exclude these additional characters?