How to serialize a Json partially? - json

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

Related

Convert Dictionary to JSON Swift

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

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.

Swift 3 parsing API response trouble

I'm trying to parse an API response in Swift an Im having trouble getting to nested objects and arrays in the response
here is my sample json
{
"Id": "10",
"Name": "PV Prediction By Site",
"Description": "",
"Permalink": "",
"Source_format": "JSON",
"Internal_function_name": "get-meteo-by-site",
"Additional_parameters": "Prediction",
"Sites": null,
"Data": [
{
"UTCDateString": "2017-05-01T20:10:33Z",
"Value": [
{
"metadata": {
"name": "Beck_Hill",
"latitude": 46.26,
"longitude": -112.44,
"height": 1926,
"timezone_abbrevation": "MDT",
"utc_timeoffset": -6,
"modelrun_utc": "2017-05-01 12:00",
"modelrun_updatetime_utc": "2017-05-01 16:41",
"kwp": 40.26,
"slope": 30,
"facing": 180,
"tracking": 0
},
"units": {
"time": "YYYY-MM-DD hh:mm",
"pvpower": "kW",
"snowcover": "mm",
"iam": "percent",
"temperature": "C"
},
"data_xmin": {
"time": [
"2017-05-01 07:00",
"2017-05-01 07:15",
"2017-05-01 07:30",
"2017-05-01 07:45",
"2017-05-01 08:00",
"2017-05-01 08:15",
"2017-05-01 08:30"
],
"pvpower_instant": [
40.26,
40.26,
40.26,
40.26,
40.26
]
}
}
]
}
]
}
And here is some of my parsing code, I can get to the first object in the "Data" array fine, but when i try to get the first object in the Value string it fails to convert the AnyObject to anything else
//get a Dictionary of sites
sitesDictionary = try JSONSerialization.jsonObject(with: decodedData, options: .allowFragments) as? [[String:AnyObject]]
CoreDataStack.sharedInstance.persistentContainer.performBackgroundTask({ (context) in
//loop thorugh all site and create SiteMO objects from them
for site in (sitesDictionary?.enumerated())! {
//SiteMO
let siteMO = SiteMO.siteInfo(siteInfo: site.element, inManagedObjectContext: context)!
let siteFeedsDictionary = site.element["Feeds"] as! [[String:AnyObject]]
//loop through every feed object and create FeedMO objects from them
for feed in siteFeedsDictionary.enumerated() {
//FeedMO
let feedMO = FeedMO.feedInfo(feedInfo: feed.element, site: siteMO, inManagedObjectContext: context)!
//what type of data is in the feed?
switch feedMO.additionalParameters! {
case "Weather":
//its a feed with a Weather object
print("There should be a WeatherMO created Here")
case "Prediction":
//its a feed with a Prediction object
let dataArray = feed.element["Data"] as? [[String:AnyObject]]
I need some data out of the "metadata" "units" and "data_xmin" objects
For metadata
result[“Data”][0][“Value”][0]

How to parse data which starts with an array [?

So in my swift 3 xcode project, I want to parse some data using JSOmN by consuming a web service called "http://tour-pedia.org/api/"
And the data within it for example is set like this:
[
{
"address": "Science Park 904",
"category": "attraction",
"id": 30884,
"lat": 52.355320008998,
"lng": 4.9574317242814,
"location": "Amsterdam",
"name": "Dakterras Science Park",
"originalId": "4d8b3370bc848cfa1043ea2b",
"polarity": 0,
"subCategory": "Scenic Lookout",
},
{
"address": "Science Park 201",
"category": "attraction",
"id": 30661,
"lat": 52.356701093273,
"lng": 4.9529844809109,
"location": "Amsterdam",
"name": "In 'de Natuur' rondom Science Park",
"originalId": "4da2ede7c6e96ea85e1ede5d",
"polarity": 0,
"subCategory": "Field",
}
]
I want to use the address, location and name field.
so far i have done this:
func fetchInfos(){
let urlRequest = URLRequest(url: URL(string: "http://tour-pedia.org/api/")!)
let task = URLSession.shared.dataTask(with: urlRequest){ (data,response,error) in
if error != nil {
print(error)
return
}
do{
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject]
} catch let error {
print(error)
}
}
}
but i don't know how to continue on from here.
Any help will be appreciated, thank you!
Let us assume your string s is the json with sqaure brackets
String s = "[{\"a\":\"b\"}]";
s = s.substring(1, s.length() - 1);
//do all your processing on s now, as the sqaure brackets will be removed !!

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.