1

I have JSON Respose from API like this:

[{
  "id":"6",
  "name":"Лилия",
  "description":"Сауна "Лилия" ждёт всех тех, кто хочет отдохнуть от суеты в специально созданной для этого атмосфере тепла и уюта. В Вашем распоряжении 3 жаркие сауны, комнаты отдыха, 3 бассейна (один длиной 14 м), в котором Вы можете прекрасно поплавать. Для Вашего удобства всегда в продаже берёзовые и дубовые веники. При желании можно заказать блюда европейской кухни и напитки прямо в сауну. Рады видеть Вас в нашей сауне круглосуточно! Стоимость саун от 350 руб./час - более подробную информацию уточняйте у администратора"
}]

Trying to decode it to my Model But getting error:

dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "Badly formed object around character 58." UserInfo={NSDebugDescription=Badly formed object around character 58.})))

My code:

class NetworkService {
    var companies = [Company]()
    let session = URLSession(configuration: .default)

    func getCompanies(stringUrl: String) {

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

        let task = session.dataTask(with: url) { (data, response, error) in
            guard let dataResponse = data, error == nil else {
                    print(error?.localizedDescription ?? "Response Error")
                    return
            }

            do {
                self.companies = try JSONDecoder().decode(Array<Company>.self, from: dataResponse)
            } catch let parsingError {
                print("error", parsingError)
            }
        }

        task.resume()
    }
}

Model:

struct Company: Codable {
    let name: String
    let description: String?
}
2
  • Is is a coincidence that the word in quotes in description is the same as the one in name or is that a pattern? Commented Jun 15, 2019 at 18:01
  • it's a coincidence. translate is something like this: { "name": "Lilia", "descripition": "Sauna "Lilia" is waiting for all of you who wanted to has a rest ...." } Commented Jun 15, 2019 at 18:29

2 Answers 2

2

Correct json ( you need to add escaping \ before any " inside description 's key value)

[{
    "id": "6",
    "name": "Лилия",
    "description": "Сауна \" Лилия \" ждёт всех тех, кто хочет отдохнуть от суеты в специально созданной для этого атмосфере тепла и уюта. В Вашем распоряжении 3 жаркие сауны, комнаты отдыха, 3 бассейна (один длиной 14 м), в котором Вы можете прекрасно поплавать. Для Вашего удобства всегда в продаже берёзовые и дубовые веники. При желании можно заказать блюда европейской кухни и напитки прямо в сауну. Рады видеть Вас в нашей сауне круглосуточно! Стоимость саун от 350 руб./час - более подробную информацию уточняйте у администратора"
}]

Try

let str = String(data:data, encoding: .utf8)
let actual = str.replacingOccurrences(of: "Сауна \" Лилия \"", with: "Сауна \\" Лилия \\"")

Then change this

 self.companies = try JSONDecoder().decode(Array<Company>.self, from: Data(actual.utf8))
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but I don't have access to API
any workaround will work for this specific response try to contact the web developer to change that response
0

Попытаюсь я:

import Foundation

let badJsonString = "{\"id\":\"2\",\"description\":\"any \"bad\" description\"}"
let okJsonString  = badJsonString.replacingOccurrences(of: #"(?<= )\"|\"(?= )"#, with: "'", options: .regularExpression)
let jsonData = try JSONSerialization.jsonObject(with: Data(okJsonString.utf8))
print(jsonData)

1 Comment

This is just code without any description, please explain how this solves the problem

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.