-
-
Save robertmryan/03542e2da539ad7f51c2540bafdad97e to your computer and use it in GitHub Desktop.
struct Cost: Codable { | |
let id: String | |
let label: String | |
let value: String | |
} | |
let cost = Cost(id: "something", label: "something", value: "something") | |
let jsonData = try! JSONEncoder().encode(cost) // this works fine | |
let object = try! JSONSerialization.jsonObject(with: jsonData) // this works fine |
It’s either:
let foo = "some \"quoted\" string"
or you can use extended string delimiters with #"
and "#
:
let foo = #"some "quoted" string"#
or you can use the multiline string literal, with """
(note, three, not two "
):
let foo = """
some "quoted" string
"""
If you want to do string interpolation, it’s either:
let bar = "the value is \(foo)"
Or within the extended string delimiters, you can use \#(foo)
for interpolation:
let bar = #"the value is \#(foo)"#
Or you can use the multiline string literal with the standard string interpolation syntax:
let bar = """
the value is \(foo)
"""
let order = NewOrder(billing: billing, couponLine: [], customerId: customerId, lineItems: lineItems, paymentMethod: paymentMethod, paymentMethodTitle: paymentMethodTitle, setPaid: false, shipping: shipping, shippingLines: shippingLine) let jsonData = try! JSONEncoder().encode(order) print(JSONSerialization.isValidJSONObject(jsonData))
i was wrong,
isValidJSONObject
still printsfalse
You misunderstand the purpose of isValidJSONObject
. This method is just telling you whether you can take the object and pass it to JSONSerialization.data(withJSONObject:)
without failing. Unlike JSONEncoder
, JSONSerialization
is extremely limited in terms of what it can encode; see “Overview” section of JSONSerialization
documentation for specifics.
But you pass it an object to be encoded, not the Data
that is the raw JSON:
let foo = ["a": 1]
print(JSONSerialization.isValidJSONObject(foo)) // true
let bar = ["a", "b", "c"]
print(JSONSerialization.isValidJSONObject(bar)) // true
let baz = 42
print(JSONSerialization.isValidJSONObject(baz)) // false because it has to be array or dictionary
let qux = [NSObject()]
print(JSONSerialization.isValidJSONObject(qux)) // false because the object in the array cannot be represented
If you want to see if the Data
is valid JSON, you’ll have to actually attempt the decode...
the problem solved, it was just a type mismatch, one of the numeric parameters most be string but I send it in Integer.
thanks a lot for your helps my friend, I so sorry for wasting your time.
👍
hi again my friend, I'm have issue with my network layer, would you please help me???
Go ahead an add your question here. Worst case scenario, if it’s too complicated, I might suggest that you post it as a proper question on StackOverflow, as I’m buried right now.
I really don't know about it complication, I will ask and you take decision that its complicated or not.
I have APIClient in my project and this is the code:
protocol APIClientType {
func request<M: Codable>(_ endpoint: URLRequestConvertible) -> Single<M>
}
final class NewAPIClient: NSObject, URLSessionDelegate, APIClientType {
var session: URLSession!
override init() {
super.init()
let urlsession = URLSession(configuration: .default, delegate: self, delegateQueue: OperationQueue.main)
urlsession.configuration.allowsCellularAccess = true
urlsession.configuration.timeoutIntervalForRequest = TimeInterval(10.0)
self.session = urlsession
}
func request<M: Codable>(_ endpoint: URLRequestConvertible) -> Single<M> {
return Single<M>.create { [unowned self] single in
let request = endpoint.request()
#if DEBUG
print("REQUEST: \(debugPrint(request))")
#endif
let task = self.session.dataTask(with: request) { (data, response, error) in
if let responseError = error {
single(.error(responseError))
}
#if DEBUG
print("RESPONSE: \(debugPrint(response ?? "NULL"))")
#endif
if let httpResponse = response as? HTTPURLResponse {
switch httpResponse.statusCode {
case 200, 201:
guard let data = data else {
break
}
do {
let model = try JSONDecoder().decode(M.self, from: data)
single(.success(model))
} catch let myJSONError {
single(.error(myJSONError))
}
case 404:
single(.error(APIError.NotFound))
default:
break
}
}
}
task.resume()
return Disposables.create {
task.cancel()
}
}
}
}
in 2 case of web services the response is simple text not a json, something like "the task done", my issue is when I intent to get this responses the " request " function returns myJSONError, how can I modify this class to return a simple string response?
i was wrong,
isValidJSONObject
still printsfalse