Allow JSON fragments with Decodable












1















import UIKit

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
//@IBOutlet weak var ingredientText: UILabel!

struct Recipes: Decodable {
let recipe_id:String?
let image_url:String?
let source_url:String?
let f2f_url:String?
let title:String?
let publisher:String?
let social_rank:Float64?
let page:Int?
let ingredients:[String]?

private enum CodingKeys: String, CodingKey{
case recipe_id = "recipe_id"
case image_url = "image_url"
case source_url = "source_url"
case f2f_url = "f2f_url"
case title = "title"
case publisher = "publisher"
case social_rank = "social_rank"
case page = "page"
case ingredients = "ingredients"
}
}

var recipes = [Recipes]()
var food = "chicken"
var food2 = "peas"
var food3 = "onions"
//var recipeData = [Recipe]

@IBOutlet weak var tableView: UITableView!

fileprivate func getRecipes() {
let jsonURL = "http://food2fork.com/api/search?key=264045e3ff7b84ee346eb20e1642d9d9264045e3ff7b84ee346eb20e1642d9d9&food=chicken&food2=onions&food3=peas"

guard let url = URL(string: jsonURL) else{return}

URLSession.shared.dataTask(with: url) {(data, _ , err) in
DispatchQueue.main.async {
if let err = err{
print("failed to get data from URL",err)
return
}
guard let data = data else{return}

do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
self.recipes = try decoder.decode([Recipes].self, from: data)
self.tableView.reloadData()
}catch let jsonERR {
print("Failed to decode",jsonERR)
}
}
}.resume()
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return recipes.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cell")

let recipe = recipes[indexPath.row]
cell.textLabel?.text = recipe.title
return cell
}

override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.prefersLargeTitles = true
navigationItem.title = "Ingredients"
getRecipes()
}
}


I am getting the error:




JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.})))











share|improve this question

























  • Your URL gives 403 FORBIDDEN Error..... check status code....

    – Vishal Patel
    Nov 13 '18 at 6:05











  • Thanks Vishal. The wrong API key was given in the example.

    – Jonathan Jordan
    Nov 13 '18 at 6:20
















1















import UIKit

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
//@IBOutlet weak var ingredientText: UILabel!

struct Recipes: Decodable {
let recipe_id:String?
let image_url:String?
let source_url:String?
let f2f_url:String?
let title:String?
let publisher:String?
let social_rank:Float64?
let page:Int?
let ingredients:[String]?

private enum CodingKeys: String, CodingKey{
case recipe_id = "recipe_id"
case image_url = "image_url"
case source_url = "source_url"
case f2f_url = "f2f_url"
case title = "title"
case publisher = "publisher"
case social_rank = "social_rank"
case page = "page"
case ingredients = "ingredients"
}
}

var recipes = [Recipes]()
var food = "chicken"
var food2 = "peas"
var food3 = "onions"
//var recipeData = [Recipe]

@IBOutlet weak var tableView: UITableView!

fileprivate func getRecipes() {
let jsonURL = "http://food2fork.com/api/search?key=264045e3ff7b84ee346eb20e1642d9d9264045e3ff7b84ee346eb20e1642d9d9&food=chicken&food2=onions&food3=peas"

guard let url = URL(string: jsonURL) else{return}

URLSession.shared.dataTask(with: url) {(data, _ , err) in
DispatchQueue.main.async {
if let err = err{
print("failed to get data from URL",err)
return
}
guard let data = data else{return}

do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
self.recipes = try decoder.decode([Recipes].self, from: data)
self.tableView.reloadData()
}catch let jsonERR {
print("Failed to decode",jsonERR)
}
}
}.resume()
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return recipes.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cell")

let recipe = recipes[indexPath.row]
cell.textLabel?.text = recipe.title
return cell
}

override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.prefersLargeTitles = true
navigationItem.title = "Ingredients"
getRecipes()
}
}


I am getting the error:




JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.})))











share|improve this question

























  • Your URL gives 403 FORBIDDEN Error..... check status code....

    – Vishal Patel
    Nov 13 '18 at 6:05











  • Thanks Vishal. The wrong API key was given in the example.

    – Jonathan Jordan
    Nov 13 '18 at 6:20














1












1








1








import UIKit

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
//@IBOutlet weak var ingredientText: UILabel!

struct Recipes: Decodable {
let recipe_id:String?
let image_url:String?
let source_url:String?
let f2f_url:String?
let title:String?
let publisher:String?
let social_rank:Float64?
let page:Int?
let ingredients:[String]?

private enum CodingKeys: String, CodingKey{
case recipe_id = "recipe_id"
case image_url = "image_url"
case source_url = "source_url"
case f2f_url = "f2f_url"
case title = "title"
case publisher = "publisher"
case social_rank = "social_rank"
case page = "page"
case ingredients = "ingredients"
}
}

var recipes = [Recipes]()
var food = "chicken"
var food2 = "peas"
var food3 = "onions"
//var recipeData = [Recipe]

@IBOutlet weak var tableView: UITableView!

fileprivate func getRecipes() {
let jsonURL = "http://food2fork.com/api/search?key=264045e3ff7b84ee346eb20e1642d9d9264045e3ff7b84ee346eb20e1642d9d9&food=chicken&food2=onions&food3=peas"

guard let url = URL(string: jsonURL) else{return}

URLSession.shared.dataTask(with: url) {(data, _ , err) in
DispatchQueue.main.async {
if let err = err{
print("failed to get data from URL",err)
return
}
guard let data = data else{return}

do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
self.recipes = try decoder.decode([Recipes].self, from: data)
self.tableView.reloadData()
}catch let jsonERR {
print("Failed to decode",jsonERR)
}
}
}.resume()
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return recipes.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cell")

let recipe = recipes[indexPath.row]
cell.textLabel?.text = recipe.title
return cell
}

override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.prefersLargeTitles = true
navigationItem.title = "Ingredients"
getRecipes()
}
}


I am getting the error:




JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.})))











share|improve this question
















import UIKit

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
//@IBOutlet weak var ingredientText: UILabel!

struct Recipes: Decodable {
let recipe_id:String?
let image_url:String?
let source_url:String?
let f2f_url:String?
let title:String?
let publisher:String?
let social_rank:Float64?
let page:Int?
let ingredients:[String]?

private enum CodingKeys: String, CodingKey{
case recipe_id = "recipe_id"
case image_url = "image_url"
case source_url = "source_url"
case f2f_url = "f2f_url"
case title = "title"
case publisher = "publisher"
case social_rank = "social_rank"
case page = "page"
case ingredients = "ingredients"
}
}

var recipes = [Recipes]()
var food = "chicken"
var food2 = "peas"
var food3 = "onions"
//var recipeData = [Recipe]

@IBOutlet weak var tableView: UITableView!

fileprivate func getRecipes() {
let jsonURL = "http://food2fork.com/api/search?key=264045e3ff7b84ee346eb20e1642d9d9264045e3ff7b84ee346eb20e1642d9d9&food=chicken&food2=onions&food3=peas"

guard let url = URL(string: jsonURL) else{return}

URLSession.shared.dataTask(with: url) {(data, _ , err) in
DispatchQueue.main.async {
if let err = err{
print("failed to get data from URL",err)
return
}
guard let data = data else{return}

do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
self.recipes = try decoder.decode([Recipes].self, from: data)
self.tableView.reloadData()
}catch let jsonERR {
print("Failed to decode",jsonERR)
}
}
}.resume()
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return recipes.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cell")

let recipe = recipes[indexPath.row]
cell.textLabel?.text = recipe.title
return cell
}

override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.prefersLargeTitles = true
navigationItem.title = "Ingredients"
getRecipes()
}
}


I am getting the error:




JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.})))








json swift






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 13 '18 at 5:45









rmaddy

240k27315379




240k27315379










asked Nov 13 '18 at 5:30









Jonathan JordanJonathan Jordan

12




12













  • Your URL gives 403 FORBIDDEN Error..... check status code....

    – Vishal Patel
    Nov 13 '18 at 6:05











  • Thanks Vishal. The wrong API key was given in the example.

    – Jonathan Jordan
    Nov 13 '18 at 6:20



















  • Your URL gives 403 FORBIDDEN Error..... check status code....

    – Vishal Patel
    Nov 13 '18 at 6:05











  • Thanks Vishal. The wrong API key was given in the example.

    – Jonathan Jordan
    Nov 13 '18 at 6:20

















Your URL gives 403 FORBIDDEN Error..... check status code....

– Vishal Patel
Nov 13 '18 at 6:05





Your URL gives 403 FORBIDDEN Error..... check status code....

– Vishal Patel
Nov 13 '18 at 6:05













Thanks Vishal. The wrong API key was given in the example.

– Jonathan Jordan
Nov 13 '18 at 6:20





Thanks Vishal. The wrong API key was given in the example.

– Jonathan Jordan
Nov 13 '18 at 6:20












2 Answers
2






active

oldest

votes


















0














JSONDecoder doesn't provide any JSONSerialization.ReadingOptions.



You could make a manual check whether the first byte of the data is an opening square bracket <5b> or brace <7b>



guard let data = data, let firstByte = data.first else { return }
guard firstByte == 0x5b || firstByte == 0x7b else {
let string = String(data: data, encoding: .utf8)!
print(string)
return
}


However I'd recommend to use the response parameter to check for status code 200



URLSession.shared.dataTask(with: url) { (data, response , error) in
if let response = response as? HTTPURLResponse, response.statusCode != 200 {
print(response.statusCode)
return
}
...


Note: If the CodingKeys match exactly the struct members you can omit the CodingKeys and as you are explicitly using .convertFromSnakeCase you are encouraged to name the struct members recipeId, imageUrl, sourceUrl etc.






share|improve this answer


























  • Vadian, Thank you for your answer that did help a lot. I used your response perameter and did get the error 403, but I changed my API key and the error changed to, Failed to decode typeMismatch(Swift.Array<Any>, Swift.DecodingError.Context(codingPath: , debugDescription: "Expected to decode Array<Any> but found a dictionary instead.", underlyingError: nil))

    – Jonathan Jordan
    Nov 13 '18 at 6:17













  • If the root object is a dictionary you have to decode Recipes.self

    – vadian
    Nov 13 '18 at 7:34











  • The root object is a dictionary. Will I have to make a separate struct for the root? I am very new to swift and coding in general. I changed the [Recipes].self to Recipes.self and am now getting a type mismatch error.

    – Jonathan Jordan
    Nov 13 '18 at 7:51











  • In terms of Decodable every dictionary is a struct. So you need an extra struct for the root object.

    – vadian
    Nov 13 '18 at 7:54











  • Thank you for your help. I will try this.

    – Jonathan Jordan
    Nov 13 '18 at 7:56



















0














You want to decode [Recipe], that is, an Array of Recipe. That mean the first (non-whitespace) character in data has to be [ (to make it a JSON array), and it's not. So you need to figure out why you're getting the wrong response, and fix that problem. Try converting data to a String and printing it:



print(String(data: data, encoding: .utf8))





share|improve this answer
























  • I did that and it works. I get The top 30 recipes from food2fork api. However when I go to change the data to a string my self.recipes = try decoder.decode([Recipes].self, from: data) does not accept data as a string. Trying to look now but this was also a good point. Thank you. If you know of a post to fix this please link.

    – Jonathan Jordan
    Nov 13 '18 at 6:43











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53274397%2fallow-json-fragments-with-decodable%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














JSONDecoder doesn't provide any JSONSerialization.ReadingOptions.



You could make a manual check whether the first byte of the data is an opening square bracket <5b> or brace <7b>



guard let data = data, let firstByte = data.first else { return }
guard firstByte == 0x5b || firstByte == 0x7b else {
let string = String(data: data, encoding: .utf8)!
print(string)
return
}


However I'd recommend to use the response parameter to check for status code 200



URLSession.shared.dataTask(with: url) { (data, response , error) in
if let response = response as? HTTPURLResponse, response.statusCode != 200 {
print(response.statusCode)
return
}
...


Note: If the CodingKeys match exactly the struct members you can omit the CodingKeys and as you are explicitly using .convertFromSnakeCase you are encouraged to name the struct members recipeId, imageUrl, sourceUrl etc.






share|improve this answer


























  • Vadian, Thank you for your answer that did help a lot. I used your response perameter and did get the error 403, but I changed my API key and the error changed to, Failed to decode typeMismatch(Swift.Array<Any>, Swift.DecodingError.Context(codingPath: , debugDescription: "Expected to decode Array<Any> but found a dictionary instead.", underlyingError: nil))

    – Jonathan Jordan
    Nov 13 '18 at 6:17













  • If the root object is a dictionary you have to decode Recipes.self

    – vadian
    Nov 13 '18 at 7:34











  • The root object is a dictionary. Will I have to make a separate struct for the root? I am very new to swift and coding in general. I changed the [Recipes].self to Recipes.self and am now getting a type mismatch error.

    – Jonathan Jordan
    Nov 13 '18 at 7:51











  • In terms of Decodable every dictionary is a struct. So you need an extra struct for the root object.

    – vadian
    Nov 13 '18 at 7:54











  • Thank you for your help. I will try this.

    – Jonathan Jordan
    Nov 13 '18 at 7:56
















0














JSONDecoder doesn't provide any JSONSerialization.ReadingOptions.



You could make a manual check whether the first byte of the data is an opening square bracket <5b> or brace <7b>



guard let data = data, let firstByte = data.first else { return }
guard firstByte == 0x5b || firstByte == 0x7b else {
let string = String(data: data, encoding: .utf8)!
print(string)
return
}


However I'd recommend to use the response parameter to check for status code 200



URLSession.shared.dataTask(with: url) { (data, response , error) in
if let response = response as? HTTPURLResponse, response.statusCode != 200 {
print(response.statusCode)
return
}
...


Note: If the CodingKeys match exactly the struct members you can omit the CodingKeys and as you are explicitly using .convertFromSnakeCase you are encouraged to name the struct members recipeId, imageUrl, sourceUrl etc.






share|improve this answer


























  • Vadian, Thank you for your answer that did help a lot. I used your response perameter and did get the error 403, but I changed my API key and the error changed to, Failed to decode typeMismatch(Swift.Array<Any>, Swift.DecodingError.Context(codingPath: , debugDescription: "Expected to decode Array<Any> but found a dictionary instead.", underlyingError: nil))

    – Jonathan Jordan
    Nov 13 '18 at 6:17













  • If the root object is a dictionary you have to decode Recipes.self

    – vadian
    Nov 13 '18 at 7:34











  • The root object is a dictionary. Will I have to make a separate struct for the root? I am very new to swift and coding in general. I changed the [Recipes].self to Recipes.self and am now getting a type mismatch error.

    – Jonathan Jordan
    Nov 13 '18 at 7:51











  • In terms of Decodable every dictionary is a struct. So you need an extra struct for the root object.

    – vadian
    Nov 13 '18 at 7:54











  • Thank you for your help. I will try this.

    – Jonathan Jordan
    Nov 13 '18 at 7:56














0












0








0







JSONDecoder doesn't provide any JSONSerialization.ReadingOptions.



You could make a manual check whether the first byte of the data is an opening square bracket <5b> or brace <7b>



guard let data = data, let firstByte = data.first else { return }
guard firstByte == 0x5b || firstByte == 0x7b else {
let string = String(data: data, encoding: .utf8)!
print(string)
return
}


However I'd recommend to use the response parameter to check for status code 200



URLSession.shared.dataTask(with: url) { (data, response , error) in
if let response = response as? HTTPURLResponse, response.statusCode != 200 {
print(response.statusCode)
return
}
...


Note: If the CodingKeys match exactly the struct members you can omit the CodingKeys and as you are explicitly using .convertFromSnakeCase you are encouraged to name the struct members recipeId, imageUrl, sourceUrl etc.






share|improve this answer















JSONDecoder doesn't provide any JSONSerialization.ReadingOptions.



You could make a manual check whether the first byte of the data is an opening square bracket <5b> or brace <7b>



guard let data = data, let firstByte = data.first else { return }
guard firstByte == 0x5b || firstByte == 0x7b else {
let string = String(data: data, encoding: .utf8)!
print(string)
return
}


However I'd recommend to use the response parameter to check for status code 200



URLSession.shared.dataTask(with: url) { (data, response , error) in
if let response = response as? HTTPURLResponse, response.statusCode != 200 {
print(response.statusCode)
return
}
...


Note: If the CodingKeys match exactly the struct members you can omit the CodingKeys and as you are explicitly using .convertFromSnakeCase you are encouraged to name the struct members recipeId, imageUrl, sourceUrl etc.







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 13 '18 at 6:12

























answered Nov 13 '18 at 5:59









vadianvadian

146k13157175




146k13157175













  • Vadian, Thank you for your answer that did help a lot. I used your response perameter and did get the error 403, but I changed my API key and the error changed to, Failed to decode typeMismatch(Swift.Array<Any>, Swift.DecodingError.Context(codingPath: , debugDescription: "Expected to decode Array<Any> but found a dictionary instead.", underlyingError: nil))

    – Jonathan Jordan
    Nov 13 '18 at 6:17













  • If the root object is a dictionary you have to decode Recipes.self

    – vadian
    Nov 13 '18 at 7:34











  • The root object is a dictionary. Will I have to make a separate struct for the root? I am very new to swift and coding in general. I changed the [Recipes].self to Recipes.self and am now getting a type mismatch error.

    – Jonathan Jordan
    Nov 13 '18 at 7:51











  • In terms of Decodable every dictionary is a struct. So you need an extra struct for the root object.

    – vadian
    Nov 13 '18 at 7:54











  • Thank you for your help. I will try this.

    – Jonathan Jordan
    Nov 13 '18 at 7:56



















  • Vadian, Thank you for your answer that did help a lot. I used your response perameter and did get the error 403, but I changed my API key and the error changed to, Failed to decode typeMismatch(Swift.Array<Any>, Swift.DecodingError.Context(codingPath: , debugDescription: "Expected to decode Array<Any> but found a dictionary instead.", underlyingError: nil))

    – Jonathan Jordan
    Nov 13 '18 at 6:17













  • If the root object is a dictionary you have to decode Recipes.self

    – vadian
    Nov 13 '18 at 7:34











  • The root object is a dictionary. Will I have to make a separate struct for the root? I am very new to swift and coding in general. I changed the [Recipes].self to Recipes.self and am now getting a type mismatch error.

    – Jonathan Jordan
    Nov 13 '18 at 7:51











  • In terms of Decodable every dictionary is a struct. So you need an extra struct for the root object.

    – vadian
    Nov 13 '18 at 7:54











  • Thank you for your help. I will try this.

    – Jonathan Jordan
    Nov 13 '18 at 7:56

















Vadian, Thank you for your answer that did help a lot. I used your response perameter and did get the error 403, but I changed my API key and the error changed to, Failed to decode typeMismatch(Swift.Array<Any>, Swift.DecodingError.Context(codingPath: , debugDescription: "Expected to decode Array<Any> but found a dictionary instead.", underlyingError: nil))

– Jonathan Jordan
Nov 13 '18 at 6:17







Vadian, Thank you for your answer that did help a lot. I used your response perameter and did get the error 403, but I changed my API key and the error changed to, Failed to decode typeMismatch(Swift.Array<Any>, Swift.DecodingError.Context(codingPath: , debugDescription: "Expected to decode Array<Any> but found a dictionary instead.", underlyingError: nil))

– Jonathan Jordan
Nov 13 '18 at 6:17















If the root object is a dictionary you have to decode Recipes.self

– vadian
Nov 13 '18 at 7:34





If the root object is a dictionary you have to decode Recipes.self

– vadian
Nov 13 '18 at 7:34













The root object is a dictionary. Will I have to make a separate struct for the root? I am very new to swift and coding in general. I changed the [Recipes].self to Recipes.self and am now getting a type mismatch error.

– Jonathan Jordan
Nov 13 '18 at 7:51





The root object is a dictionary. Will I have to make a separate struct for the root? I am very new to swift and coding in general. I changed the [Recipes].self to Recipes.self and am now getting a type mismatch error.

– Jonathan Jordan
Nov 13 '18 at 7:51













In terms of Decodable every dictionary is a struct. So you need an extra struct for the root object.

– vadian
Nov 13 '18 at 7:54





In terms of Decodable every dictionary is a struct. So you need an extra struct for the root object.

– vadian
Nov 13 '18 at 7:54













Thank you for your help. I will try this.

– Jonathan Jordan
Nov 13 '18 at 7:56





Thank you for your help. I will try this.

– Jonathan Jordan
Nov 13 '18 at 7:56













0














You want to decode [Recipe], that is, an Array of Recipe. That mean the first (non-whitespace) character in data has to be [ (to make it a JSON array), and it's not. So you need to figure out why you're getting the wrong response, and fix that problem. Try converting data to a String and printing it:



print(String(data: data, encoding: .utf8))





share|improve this answer
























  • I did that and it works. I get The top 30 recipes from food2fork api. However when I go to change the data to a string my self.recipes = try decoder.decode([Recipes].self, from: data) does not accept data as a string. Trying to look now but this was also a good point. Thank you. If you know of a post to fix this please link.

    – Jonathan Jordan
    Nov 13 '18 at 6:43
















0














You want to decode [Recipe], that is, an Array of Recipe. That mean the first (non-whitespace) character in data has to be [ (to make it a JSON array), and it's not. So you need to figure out why you're getting the wrong response, and fix that problem. Try converting data to a String and printing it:



print(String(data: data, encoding: .utf8))





share|improve this answer
























  • I did that and it works. I get The top 30 recipes from food2fork api. However when I go to change the data to a string my self.recipes = try decoder.decode([Recipes].self, from: data) does not accept data as a string. Trying to look now but this was also a good point. Thank you. If you know of a post to fix this please link.

    – Jonathan Jordan
    Nov 13 '18 at 6:43














0












0








0







You want to decode [Recipe], that is, an Array of Recipe. That mean the first (non-whitespace) character in data has to be [ (to make it a JSON array), and it's not. So you need to figure out why you're getting the wrong response, and fix that problem. Try converting data to a String and printing it:



print(String(data: data, encoding: .utf8))





share|improve this answer













You want to decode [Recipe], that is, an Array of Recipe. That mean the first (non-whitespace) character in data has to be [ (to make it a JSON array), and it's not. So you need to figure out why you're getting the wrong response, and fix that problem. Try converting data to a String and printing it:



print(String(data: data, encoding: .utf8))






share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 13 '18 at 6:04









rob mayoffrob mayoff

292k41591640




292k41591640













  • I did that and it works. I get The top 30 recipes from food2fork api. However when I go to change the data to a string my self.recipes = try decoder.decode([Recipes].self, from: data) does not accept data as a string. Trying to look now but this was also a good point. Thank you. If you know of a post to fix this please link.

    – Jonathan Jordan
    Nov 13 '18 at 6:43



















  • I did that and it works. I get The top 30 recipes from food2fork api. However when I go to change the data to a string my self.recipes = try decoder.decode([Recipes].self, from: data) does not accept data as a string. Trying to look now but this was also a good point. Thank you. If you know of a post to fix this please link.

    – Jonathan Jordan
    Nov 13 '18 at 6:43

















I did that and it works. I get The top 30 recipes from food2fork api. However when I go to change the data to a string my self.recipes = try decoder.decode([Recipes].self, from: data) does not accept data as a string. Trying to look now but this was also a good point. Thank you. If you know of a post to fix this please link.

– Jonathan Jordan
Nov 13 '18 at 6:43





I did that and it works. I get The top 30 recipes from food2fork api. However when I go to change the data to a string my self.recipes = try decoder.decode([Recipes].self, from: data) does not accept data as a string. Trying to look now but this was also a good point. Thank you. If you know of a post to fix this please link.

– Jonathan Jordan
Nov 13 '18 at 6:43


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53274397%2fallow-json-fragments-with-decodable%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Full-time equivalent

さくらももこ

13 indicted, 8 arrested in Calif. drug cartel investigation