PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, December 3, 2022

[FIXED] How do I convert a dictionary to top level JSON in Swift?

 December 03, 2022     dictionary, json, jsonencoder, swift     No comments   

Issue

I have this model in Swift:

struct EventModel: Codable {
    var eventType: String
    var eventName: String?
    var attributes: [String: String]?
}

Is it possible to move the attributes to the top level when I convert it to JSON? Example:

var model = EventModel(eventType: "type", 
                       eventName: "name", 
                       attributes: ["attribute1": "One", "attribute2": "Two"]) 

becomes

{
   "eventType" : "type",
   "eventName" : "name",
   "attribute1" : "One",
   "attribute2" : "Two"
}

Solution

First, encode the static keys, then encode the attributes into the same encoder:

extension EventModel: Encodable {
    enum CodingKeys: CodingKey {
        case eventType, eventName
    }

    func encode(to encoder: Encoder) throws {
        // Encode the normal stuff
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(eventType, forKey: .eventType)
        try container.encode(eventName, forKey: .eventName)

        // Then have the attributes dictionary encode itself
        try attributes?.encode(to: encoder)

    }
}


Answered By - Rob Napier
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing