swift - 将文本文件的内容作为 JSON 传递给 httpBody
问题描述
想通了,见下文:
我正在尝试创建一个可以将文本文件的内容快速传递给 http POST 请求的程序。我正在为我在文本文件中运行的 API 查询存储过滤器,并希望将它们作为 JSON 对象(?我认为,无论如何)传递给请求中的 request.httpBody。我在将 txt 文件转换为 httpBody 可以接受的数据(json 对象?)时遇到问题。
这里是一个示例 txt 文件。使用 OR 逻辑组合同一数组中的过滤器。过滤器数组使用 AND 逻辑组合,因此我必须考虑这两种情况。:
zero_RC.txt
{
"query": "Zero Response Code",
"filters": [
{
"filters": [
{
"field": "inventoryState",
"value": "CONFIRMED",
"type": "IN"
},
{
"field": "responseCode",
"value": "0",
"type": "EQ"
},
{
"field": "exception",
"value": "DNS lookup failed",
"type": "EQ"
}]
}]
}
这是我要开始工作的块。我相信我需要一个 JSON 对象,并且可以在下面的请求中将它传递给 httpBody。但是,仍然是这方面的初学者。
// get JSON, somehow
let file = Bundle.main.path(forResource: "zero_RC", ofType: "txt")
let jsonData = file!.data(using: .utf8)
let JSON = try! JSONSerialization.data(withJSONObject: jsonData as Any, options: [])
if JSONSerialization.isValidJSONObject(JSON) {
print("Oh Yeah")
} else {
print("Nah bud, that ain't working")
}
// make the request
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("Basic \(loginData!)", forHTTPHeaderField: "Authorization")
request.httpBody = JSON
那么我是在获取一个字符串并转换为数据,然后再转换为 JSON 对象吗?我对如何最好地做到这一点感到非常困惑。我已经搜索和搜索了,我发现的只是解析文章,这并不完全有帮助。
提前谢谢。
回答:
问题出在 request.setValue 中。我需要使用Content-Type
而不是Accept
.
// get JSON
let path = Bundle.main.path(forResource: "zero_RC", ofType: "txt")
let data = try! Data(contentsOf: URL(fileURLWithPath: path!), options: .mappedIfSafe)
// make the request
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("Basic \(loginData!)", forHTTPHeaderField: "Authorization")
request.httpBody = data
解决方案
这是解决方案,首先我们将您的 json 文件解码为数据模型,然后将该数据模型对象编码为 httpBody。
let path = Bundle.main.path(forResource: "zero_RC", ofType: "txt")
let data = try! Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
let jsonDecoder = JSONDecoder()
let json = try! jsonDecoder.decode(JsonObjModel.self, from: data)
// now encoding that jsonData to the http body
let encoder = JSONEncoder()
urlRequest.httpBody = try! encoder.encode(json)
'JsonObjModel' 将如下
// MARK: - JSONObjModel
struct JSONObjModel: Codable {
let query: String
let filters: [JSONObjModelFilter]
}
// MARK: - JSONObjModelFilter
struct JSONObjModelFilter: Codable {
let filters: [FilterFilter]
}
// MARK: - FilterFilter
struct FilterFilter: Codable {
let field, value, type: String
}
推荐阅读
- python - 尝试在 python 中调用 pl/sql 函数,但收到带有 to_date 的 ORA-01858 错误
- r - 将 mutate_at 有条件地应用于 R 中数据帧中的特定行
- java - 如何计算使总和最小化的点?
- amazon-web-services - 具有合适实时示例的主路由表和自定义路由表之间的主要区别是什么?
- javascript - Jquery获取最近类的未定义值
- assembly - 汇编语言中JP和JPE或JNP和JPO之间的区别
- c# - 为什么控制器方法在浏览器中按顺序处理
- android - Google Places API Autocomplete 仅获取城市列表
- z3 - Z3 Solver 超时与抽象环
- laravel-5 - 如何控制 webview 和 web 浏览器之间的 webapp 访问?