![]() Run the playground and inspect snakeString. ![]() convertFromSnakeCase to decode snakeData. Open Snake case vs camel case and add the following code just after the encoder and decoder are created, before they get used:Įncoder.keyEncodingStrategy =. The Gifts department API has switched from camel case (which looksLikeThis) to snake case (which looks_like_this_instead) to format keys for its JSON.īut all of the stored properties of Employee and Toy use camel case only! Fortunately, Foundation has you covered. Time for your next challenge! Switching Between Snake Case and Camel Case Formats Press the blue play button to run the Playground and see the results. Here, you’ve used decode(_:from:) to decode data back to Employee… and you’ve made your employee very happy. Let sameEmployee = try code(lf, from: data) The encoding process generates valid data, so the Gifts department can recreate the employee: To see results, you can print values to the debugger console or click the Show Result button in the results sidebar. Note: Press Shift-Return to run the playground up to your current line, or click the blue play button. Create a string from the encoded data to visualize it.Encode employee to JSON with encode(_:) (I told you it was easy!).Let string = String(data: data, encoding. Add the following code to send your employee’s data to the Gifts department: The Gifts department gives employees their favorite toys as birthday gifts. If your property names match your JSON field names, and your properties are all Codable, then you can convert to or from JSON very easily. ![]() The JSON nests name inside favoriteToy and all the JSON keys are the same as the Employee and Toy stored properties, so you can easily understand the JSON structure based on your data types hierarchy. The JSON structure of your encoded employee matches the Employee struct: Time for your first encoding and decoding challenge! Encoding and Decoding Nested TypesĮmployee contains a Toy property - it’s a nested type. Note: You can encode codable types to various formats such as Property Lists (PLists), XML or JSON, but for this tutorial you’ll only work with JSON.Īdd a JSONEncoder and a JSONDecoder to handle JSON encoding and decoding of toys and employees: ![]()
0 Comments
Leave a Reply. |