反馈json格式错误

问题描述 投票:1回答:1

这是我的反馈json字符串:

{"name":"abc", "cardNumber":"1234567890", "data": [{A data},{B data}...]} 

我用这个函数发送数据,然后得到json和encode:

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

This json can be format and read in android if I use JSONObject.getJSONArray("myValue")... I try to use print(data)(without json encode) to show if there is any data in feedback and I get 400byte in console, so I'm sure there is data send back to me. UPDATE 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发送出去。

UPDATE 12/28 new After trying so much, I found string can get the feedback, but the value of name is Chinese word, other value is English and number, only name is unreadable, now I'm checking which String.Encoding will work, then if I encode it success, I will try to format to json Array.
ios json swift
1个回答
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()

}

© www.soinside.com 2019 - 2024. All rights reserved.