Convert Dictionary to JSON Swift - json

I am new to the iOS development , I have dictionary as given below, I want to convert it to JSON, pass it to API
["checkinDate": "",
"data": [{
"abc": 2,
"cde": 13,
"edt": 1,
"shortName": "OCC"
}],
"incidentDescription": "",
"store": "ABD"
]
Code:
let jsonData = try! JSONSerialization.data(withJSONObject: saveDict)
let jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue)
I have used below code but it is giving output as
"materialList": ["{\"abc\":2,\"cde\":13,\"edt\":1,\"shortName\":\"OCC\"}"],
"checkinDate": "",
"incidentDescription": "",
It is add \ while converting array of dictionary to JSON

Related

How to serialize a Json partially?

I have a huge json (20 mb, 6000+ records) that If I use decode it takes ages, then I started using serialize to try to parse it in pieces. But I'm having trouble to parse it (getting null when I serialize it, funny enough I don't specify as? [String:Any] I actually get the json)
is there a better way to parse a Json partially?
Json structure
[
{
"page": 1,
"total": 100,
"data": [
{
"address": "677 Quincy Street #1B",
"neighborhood": "Stuyvesant Heights",
"zipcode": "11221",
"latitude": 40.68935935,
"longitude": -73.93179845,
"bedroom": "2 beds",
"bath": "1.5 baths",
"area": null,
"status": "current",
"photos": [
"https://photos.zillowstatic.com/fp/b444ec7e07f1bb83f27c6dfa2167e92a-se_extra_large_1500_800.jpg"
],
"video": null,
"description": "NO FEE!!Luxury 2 BR / 1.5 Bath DUPLEX Apartment",
"new_listing": 1,
"date_available": "Available Now",
"open_house": null,
"price": 2999,
"dishwasher": false,
"washer_and_dryer": false,
"pets_allowed": true,
"live_in_super": false,
"elevator": false,
"url": "https://streeteasy.com/building/677-quincy-street-brooklyn/1b"
},
]
}
]
I made it work, but sadly serialization doesn't help with the load speed, I was thinking to do "pagination with the first 100 items" but swift needs to parse the entire json first.
//serialization baby!
let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [[String:Any]]
//make it an array
let first100Listings = json!.first!["data"] as? NSArray
let jsonData = try JSONSerialization.data(withJSONObject: first100Listings!, options: [])
let responseModel = try JSONDecoder().decode([Listings].self, from: jsonData)
self.listingsZ = responseModel

How to Convert Swift JSON / Dict Key camel to underscore without Codable?

I want convert:
{
"userNickname": "whatever",
"userId": "123",
"date": "2021-03-25T16:10:00Z"
}
to
{
"user_nick_name": "whatever",
"user_id": "123",
"date": "2021-03-25T16:10:00Z"
}
But all the methods found so far are based on the codable protocol, or bugs generated during the conversion process, do you have any good suggestions?
First decode the json normally and then encode it with a keyEncodingStrategy set to convertToSnakeCase
Example (with non existing error handling)
json = """
{
"userNickname": "whatever",
"userId": "123",
"date": "2021-03-25T16:10:00Z"
}
""".data(using: .utf8)!
let result = try! JSONDecoder().decode([String:String].self, from:json)
let encoder = JSONEncoder()
encoder.keyEncodingStrategy = .convertToSnakeCase
let data = try! encoder.encode(result)
if let str = String(data: data, encoding: .utf8) {
print(str)
}

Getting invalid json when calling JSONSerialization in Swift

I am trying to access a URL and parse the JSON output. Printing JSON in utf8 encoding
Code:
let urlString:String = "https://developer.nrel.gov/api/.../"
let pvURL = URL(string: urlString)
let dataTask = URLSession.shared.dataTask(with:pvURL!) { (data, response, error) in
do {
let json = try JSONSerialization.jsonObject(with: data!)
print(String(data: data!, encoding: .utf8)!)
}catch let err {
print("error: \(err.localizedDescription)")
}
}
dataTask.resume()
Prints the following output. I try this JSON in an online JSON parser it fails. Gives error in the first line itself.
{"inputs":{"lat":"29.93","lon":"-95.61","system_capacity":"30.30","azimuth":"180","tilt":"40","array_type":"1","module_type":"1","losses":"10"},"errors":[],"warnings":[],"version":"1.0.1","ssc_info":{"version":45,"build":"Linux 64 bit GNU/C++ Jul 7 2015 14:24:09"},"station_info":{"lat":29.93000030517578,"lon":-95.62000274658203,"elev":41.0,"tz":-6.0,"location":"None","city":"","state":"Texas","solar_resource_file":"W9562N2993.csv","distance":964},"outputs":{"ac_monthly":[3480.57373046875,3440.078369140625,3992.6513671875,3977.071533203125,4074.91357421875,3701.75,3897.655517578125,4248.00390625,4023.283447265625,4157.29931640625,3605.156005859375,3342.12890625],"poa_monthly":[139.791015625,140.18896484375,164.8218536376953,164.47149658203125,173.2971649169922,159.90576171875,169.84793090820312,186.20114135742188,173.14492797851562,176.2291717529297,148.28318786621094,136.62326049804688],"solrad_monthly":[4.509387493133545,5.006748676300049,5.316833972930908,5.4823832511901855,5.590230941772461,5.3301920890808105,5.4789652824401855,6.00648832321167,5.77149772644043,5.684812068939209,4.94277286529541,4.407201766967773],"dc_monthly":[3644.867919921875,3606.52001953125,4179.85107421875,4158.3193359375,4252.9140625,3865.03369140625,4069.092041015625,4432.62744140625,4198.369140625,4336.99609375,3767.055419921875,3490.091064453125],"ac_annual":45940.55859375,"solrad_annual":5.293959140777588,"capacity_factor":17.308107376098633}}`
whereas if I access the urlString in a browser gives valid json:
{
"inputs": {
"lat": "29.93",
"lon": "-95.61",
"system_capacity": "30.30",
"azimuth": "180",
"tilt": "40",
"array_type": "1",
"module_type": "1",
"losses": "10"
},
"errors": [],
"warnings": [],
"version": "1.0.1",
"ssc_info": {
"version": 45,
"build": "Linux 64 bit GNU/C++ Jul 7 2015 14:24:09"
},
"station_info": {
"lat": 29.93000030517578,
"lon": -95.62000274658203,
"elev": 41,
"tz": -6,
"location": "None",
"city": "",
"state": "Texas",
"solar_resource_file": "W9562N2993.csv",
"distance": 964
},
"outputs": {
"ac_monthly": [
3480.57373046875,
3440.078369140625,
3992.6513671875,
3977.071533203125,
4074.91357421875,
3701.75,
3897.655517578125,
4248.00390625,
4023.283447265625,
4157.29931640625,
3605.156005859375,
3342.12890625
],
...
}
In your code you are converting the JSON data into an JSON object(Array, Dictionary).
But In browser the JSON data is printing as String and not as JSON object(Array, Dictionary).
So if you want to print the JSON string in your code as well, you can print as like below.
let string = String(data: self, encoding: .utf8)
print("JSON String:\(String(describing: string))")
Hope it helps.

How to make Swift JSON request params

I got a problem with making a request to a server, I got a parsing error, could you help me to make the request properly?
I need to make a request like this:
"{ \"jsonrpc\": \"2.0\", \"id\": 1, \"method\": \"call\", \"params\": [ \"c36c5a835cf88e82f97dcfa5b74f53f4\",\"network.interface.wan\",\"status\", {} ] }"
My request:
["jsonrpc": "2.0", "id": 1, "method": "call", "params": [token, "network.interface.wan", "status", []]]
If you want to convert Dictionary as JSON String response then you can try like this way.
Edit: In JSON string with params array the last object is empty dictionary so you need to set last object of params array as [:] instead of []
let dic:[String:Any] = [
"jsonrpc": "2.0",
"id": 1,
"method": "call",
"params": [
"token",
"network.interface.wan",
"status", [:]
]
]
if let data = try? JSONSerialization.data(withJSONObject: dic),
let string = String(data: data, encoding: .utf8){
print(string)
}
Output
{\"method\":\"call\",\"jsonrpc\":\"2.0\",\"id\":1,\"params\":[\"token\",\"network.interface.wan\",\"status\",{}]}

Accessing JSON data in swift

I am trying to access JSON data in my swift code and I'm having trouble getting it to return correctly. Here is my JSON code:
[
{
"id": "1",
"isImage": "0",
"name": "test name",
"post": "test post",
"time": "10:27",
"ip": "192.168.1.1",
"city ": "Columbus",
"latlong": "39.896418,-82.9751105",
"clientID": "clientID",
"popularity": "300"
},
{
"id": "2",
"isImage": "0",
"name": "test name two",
"post": "test post two",
"time": "13:37",
"ip": "192.168.1.1",
"city ": "Columbus",
"latlong": "39.896418,-82.9751105",
"clientID": "clientID",
"popularity": "69"
}
]
I'd just like to know how to access the data by their keys json[0].['id'] or?
I am currently using this json.swift module and trying to access the data with
func jsonHandle(data: NSString) {
var parsedJSON = JSON(data)
var id = parsedJSON[0].["id"]
NSLog("\(id)")
}
but it returns nothing. Any Ideas?
You can call the JSON(string:...) rendition and eliminate the period between the [0] and the ["id"]:
func jsonHandle(data: NSString) {
let parsedJSON = JSON(string: data)
var id = parsedJSON[0]["id"]
NSLog("\(id)")
}
Or, if you had a NSData you could use the JSON(data: ...) rendition:
func jsonHandle(data: NSData) {
let parsedJSON = JSON(data: data)
let id = parsedJSON[0]["id"]
NSLog("\(id)")
}
Or, if you wanted to use the native NSJSONSerialization, rather than that third-party library, you could:
func jsonHandle(data: NSData) {
var error: NSError?
let parsedJSON = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &error) as NSArray
let id = parsedJSON[0]["id"]
NSLog("\(id)")
}
Personally, I'd lean towards the standard NSJSONSerialization approach as it's a tried and true approach, but that's your call.