I am trying to send request to server. unable get correct format JSON . please help to resolve this error.
[ "{"ProductGroupId":"994475","ProductId":"994408"}", "{"ProductGroupId":"994475","ProductId":"999737"}", "{"ProductGroupId":"994475","ProductId":"999915"}", "{"ProductGroupId":"994475","ProductId":"1194875"}" ]
self.productGroupList = json.response.result.packages[0].productGroups for index in 1..<self.productGroupList[3].products.count{
self.productGroupIdList.append(self.productGroupList[3].products[index].productGroupID) self.productGroupIdList.append(self.productGroupList[3].products[index].id) let dictionary = ["ProductGroupId": self.productGroupList[3].products[index].productGroupID, "ProductId": self.productGroupList[3].products[index].id] as [String : Any] do {
let jsonData:Data = try JSONSerialization.data( withJSONObject: dictionary, options: .fragmentsAllowed ) let jsonString = String(data: jsonData, encoding: .utf8)! self.Linelist.append(jsonString)
}
catch {
print(error.localizedDescription)
}
self.noOfCycleValuesDropDown()
}
}
}
catch{
print(error)
}
case .failure(let error): print("Error: (error.localizedDescription)") // Handle the error if needed
}
}
}
I am Expecting request like below format
[
{
"ProductGroupId": "994475",
"ProductId": "994408"
},
{
"ProductGroupId": "994475",
"ProductId": "999737"
},
{
"ProductGroupId": "994475",
"ProductId": "999915"
},
{
"ProductGroupId": "994475",
"ProductId": "999951"
},
{
"ProductGroupId": "994475",
"ProductId": "1014043"
},
{
"ProductGroupId": "994475",
"ProductId": "1194891"
}
]
2
Answers
You need to use arrays of dictionaries in swift You can try this approach I have tested it in playground
When I convert the Data to String and print it on console to check if the format is correct I get the JSON formatted string.
You can send the jsonData to server.
You can get desired JSON Data using Encodables very easily
For example create a product structre
Then try to add the values the way you were doing in loop, but for example
And to get data that you need from json use this