这是我的反馈json字符串:
{"name":"abc", "cardNumber":"1234567890", "data": [{A data},{B data}...]}
我使用此函数发送数据,然后获取json并编码:
func uploadData(word:String){
var request = URLRequest(url: url!, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 30)
request.httpMethod = "POST"
request.httpBody = word.data(using: .utf8)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let session = URLSession(configuration: URLSessionConfiguration.default)
session.dataTask(with: request, completionHandler: {(data, response, error) in
if let data = data{
do{
let data = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers)
print(data) //I want to know what is this so I print
}catch{
print(error.localizedDescription)
}
}
}).resume()
}
但控制台总是说:The data couldn't be read because it isn't in the correct format
JSONObject.getJSONArray("myValue")...
,这个json可以在android中格式化并读取 我尝试使用
print(data)
(没有json编码)来显示反馈中是否有任何数据,我在控制台中得到400byte,所以我确定有数据发回给我。 更新12/28:
{"name":"abc",
"cardNumber":"1234567890",
"data": [{day:20171228, time: 09:10:11},
{day:20171226, time: 20:00:12},
{day:20171227, time: 15:30:22}
]
}
我确定这个json可以在android中读取,我使用的接收器和发送器是vb.net,它使用sendingString = JsonConvert.SerializeObject(JSONClass)
成为json字符串,然后转换为byte发送出去。
更新12/28新 尝试了这么多之后,我发现字符串可以获得反馈,但
name
的值是中文单词,其他值是英文和数字,只有name
是不可读的,现在我检查哪个String.Encoding
将起作用,如果我对其成功编码,我将尝试格式化为json数组。
答案 0 :(得分:0)
你能尝试一下这个吗?
func uploadData(word:String){
var request = URLRequest(url: url!, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 30)
request.httpMethod = "POST"
request.httpBody = word.data(using: .utf8)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let session = URLSession(configuration: URLSessionConfiguration.default)
session.dataTask(with: request, completionHandler: {(data, response, error) in
if let data = data{
if let returnData = String(data: data!, encoding: .utf8) {
print(returnData)
} else {
print("Invalid Data Coming")
}
do{
let data = try JSONSerialization.jsonObject(with: data, options: []) as? [String: AnyObject]
print(data) //I want to know what is this so I print
}catch{
print(error.localizedDescription)
}
}
}).resume()
}