decoding and parsing nested json Swift - json

I want to parse this json file and decode and add them into list. However, couldn't find a way to that. I tried this:
struct flightsPost: Codable {
var data: flightDate
}
struct flightDate: Codable {
var origin: String
var destination: String
var price: Int
var airline: String
var flight_number: String
var departure_at: String
var return_at: String
var transfers: String
var expires_at: String
}
Couldn't find a place and how to put dates these structs. Please help I am really struggling.

Your structure is wrong. The data child is not a single object but a collection of type [String:flightDate] or if you decode it with a custom dateformatter [Date:flightDate].
struct flightsPost: Codable {
var data: [String:flightDate]
}

Related

Parse Json to nested Struct using Swift

I am trying to parse a JSON that I am receiving in my Application. The JSON Syntax is correct but I am unable to parse it into a nested Struct.
Here is my code that can be run in Playground:
let message = "{\"type\":\"something\",\"data\":{\"one\":\"first\",\"two\":\"second\",\"three\":\"third\"}}"
let jsonData = message.data(using: .utf8)!
struct Message: Decodable {
let type: String
struct data: Decodable {
var one: String
var two: String
var three: String
}
}
let receivedMessage: Message = try! JSONDecoder().decode(Message.self, from: jsonData)
The printed Result is Message(type: "something") but the data is not parsed.
How can I parse the data correctly to use it afterwards.
The nested struct/dictionary is the value for key data
struct Message: Decodable {
let type: String
let data: Nested
struct Nested: Decodable {
var one: String
var two: String
var three: String
}
}

Decode weird JSON to a normal struct?

To decode JSON, I had to create this struct:
struct Product: Decodable {
var title: String
var thumbnail: URL
var price: Price
var asin: String
}
struct Price: Decodable {
var current_price: Double
}
The decoder looks like this:
let product = try? JSONDecoder().decode(Product.self, from: data)
As you can see, JSON Price has nested property current_price, which is not very useful for me.
I have a few questions:
How can I get rid of Price and store it directly as double to Product?
Prop: thumbnail is a URL. I want to store it as a String. Is this possible?
You can try this
struct Product: Decodable {
var title: String
var thumbnail: String
var price: [String: Double]
var asin: String
var currentPrice: Double? { price["current_price"] }
}

Parse data JSON from Firebase Swift with Node

I have the following structure in Firebase as shown in the photo.
But I can't get the json format. Everything only works if I enter the node name in the model as below.
Working model for json (LNiTKMpNKHYVqTwyyY52k36Aqvo1 is entered only to show the working example)
struct SearchedUser: Decodable {
let LNiTKMpNKHYVqTwyyY52k36Aqvo1: SearchedPerson
}
struct SearchedPerson: Decodable {
let uid: String
var username: String
var name: String
var bio: String
var avatarUrl: String
let avatarBackgroundHex: String
}

My JSON decoder is not working and I'm not sure why

I'm trying to access a nested JSON variable called 'block' but I cannot seem to access it in any of the ways I've tried. Here's an example JSON message and my code:
{"account":"xrb_34tsctqcgctm8fhnpat351z4f64rgz8o9y7gwh1dutjf1r7iiwfzruawhatz","hash":"E5935C559748444D09E97D6D13FDB48B51F46A01FA9F6FB2DBD3576D684A53C6","block":"{\n \"type\": \"state\",\n \"account\": \"xrb_34tsctqcgctm8fhnpat351z4f64rgz8o9y7gwh1dutjf1r7iiwfzruawhatz\",\n \"previous\": \"78446816869EEEF4BC735B1A21AB33ED246A10303B87F0CAFD7CCD56406E0456\",\n \"representative\": \"xrb_3pczxuorp48td8645bs3m6c3xotxd3idskrenmi65rbrga5zmkemzhwkaznh\",\n \"balance\": \"320000000000000000000000000\",\n \"link\": \"8DE4EE799910E26C5E44CDD345B8C8070E1955284BC407660825B425FBEDBB6B\",\n \"link_as_account\": \"xrb_35h6xswsk694fjh6bmgmapwei3rg57ckiky61xm1ibfn6qxyugud9eo1fauk\",\n \"signature\": \"E4AF5BBDF583509DF3147004AB61FEC04F9007AC23A46A2E2E5BE4B65D0788F45F89EEC7B62D0F42144A9F5EA090EF3F58262070F07C59F1AD752B5CC3BF9D04\",\n \"work\": \"a56cb9e8d2539f73\"\n}\n","amount":"1`
struct IncomingBlock: Decodable {
var account: String
var hash: String
struct Block: Decodable {
var type: String
var previous: String
var link: String
var link_as_account: String
var representative: String
var account: String
var balance: String
var work: String
var signature: String
}
var block: Block
}
// in another file
guard let data = msg.data(using: .utf8) else { return }
guard let incomingBlock = try?JSONDecoder().decode(IncomingBlock.self, from: data) else { return }
Essentially to access the nested JSON variable block I had to decode the initial JSON message
do{
guard let data = inital_msg.data(using: .utf8) else { return }
let incomingBlock = try JSONDecoder().decode(IncomingBlock.self, from: data)
catch ...{}
and have the block's value cast to String in the model.
struct IncomingBlock: Decodable {
var account: String
var hash: String
var block: String
}
After that, I then decoded the initial messages block field once more like so
// Second JSON
let json = incomingBlock.block.data(using: .utf8)!
finally with the separated block model:
struct BlockMeta: Decodable {
var type: String
var previous: String
var link: String
var link_as_account: String
var representative: String
var account: String
var balance: String
var work: String
var signature: String
}
I could access the fields
let block = try JSONDecoder().decode(BlockMeta.self, from: json)
block.balance //returns "320000000000000000000000000"

Using Swift 4 Decodable to parse JSON with mixed property values

I am trying to update my app to use Swift 4 Decodable - and am pulling down data from a JSON api which has child values which could be:
A Child Object
A String
An Int
Here is the Json Api response:
var jsonoutput =
"""
{
"id": "124549",
"key": "TEST-32",
"fields": {
"lastViewed": "2018-02-17T21:40:38.864+0000",
"timeestimate": 26640
}
}
""".data(using: .utf8)
I have tried to parse it using the following: which works if I just reference the id and key properties which are both strings.
struct SupportDeskResponse: Decodable{
var id: String
var key: String
//var fields: [String: Any] //this is commented out as this approach doesn't work - just generated a decodable protocol error.
}
var myStruct: Any!
do {
myStruct = try JSONDecoder().decode(SupportDeskResponse.self, from: jsonoutput!)
} catch (let error) {
print(error)
}
print(myStruct)
How do I decode the fields object into my Struct?
You should create a new Struct adopting Decodable protocol like this :
struct FieldsResponse: Decodable {
var lastViewed: String
var timeestimate: Int
}
Then you can add it to your SupportDeskResponse
var fields: FieldsResponse